netstat to log file
Recently at work we ran into an issue of needing a script that would perform a netstat and dump it to a log file. We were recording UDP sessions and ended up with the following script:
echo %date% - %time%%»c:\netstatlog.txt
timeout /T 60 /NOBREAK
This script is designed to output the date/time that it ran as well as the results of a “netstat -ano” to a log file. Additionally, after it has returned those results, it then has a 1 minute timeout before returning to the beginning and running again. This was setup to run indefinitely OR until will turned it off.
There are numerous tweaks you can perform to this script, such as various netstat options as well as tweaking the timeouts to increase or decrease it.
Some other options we used were to include the tasklist feature to print the .exe’s that were using the ports. This can be accomplished two ways actually. The simplest is to change the “netstat -ano" to "netstat -anob”. This is a nice way to do it as it will keep all that data together in one dump. However if you’d like additional details (such as how much ram each service is using) you can use the tasklist option.
After the netstat line, add the following:
This will output the tasklist in the standard form. Typing "tasklist /?" in a cmd prompt will show you the additional switches you can use (such as “/V” for verbose mode).
Hope that this article helps someone else out with any scripting needs for the netstat tool. There is soo much more that can be added to this and I’m sure I will be posting further details and edits to it.