Netstat script that runs every 60 seconds and counts open connections

Here is a quick NETSTAT script that runs every 60 seconds and appends the output to c:\ports\netstat.txt.  The script exports the count of connections in a specific state.  The output is very similar to what TcpView shows you at the bottom of the GUI with connections in TIME_WAIT, ESTABLISHED, LISTENING, CLOSE_WAIT.  You can copy this to a port_count.bat and run it as a scheduled task.

@ECHO OFF
:100
ECHO %date% %time% >> c:\ports\netstat.txt
ECHO Count of all open ports: >> c:\ports\netstat.txt
netstat -an | find /c “:” >> c:\ports\netstat.txt
ECHO Count of all ports in TIME_WAIT state: >> c:\ports\netstat.txt
netstat -an | find /c “TIME_WAIT” >> c:\ports\netstat.txt
ECHO Count of all ports in ESTABLISHED state: >> c:\ports\netstat.txt
netstat -an | find /c “ESTABLISHED” >> c:\ports\netstat.txt
ECHO Count of all connections to port 8085: >> c:\ports\netstat.txt
netstat -an | find /c “:8085” >> c:\ports\netstat.txt
ECHO Count of all ports in LISTENING state: >> c:\ports\netstat.txt
netstat -an | find /c “LISTENING” >> c:\ports\netstat.txt
ECHO Count of all ports in CLOSE_WAIT state: >> c:\ports\netstat.txt
netstat -an | find /c “CLOSE_WAIT” >> c:\ports\netstat.txt
ECHO ============================================ >> c:\ports\netstat.txt
timeout /T 60
goto 100

 

OUTPUT:

Output from the above script
Fri 03/06/2015 11:23:39.32
Count of all open ports:
121
Count of all ports in TIME_WAIT state:
4
Count of all ports in ESTABLISHED state:
42
Count of all connections to port 8085:
0
Count of all ports in LISTENING state:
38
Count of all ports in CLOSE_WAIT state:
0

This entry was posted in Networking, Scripting and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *