需要固定时间间隔比如60秒运行一次检测TCP连接数,网上查了下最简单的就是用goto
语句,如果不加延时那就是死循环,在文件里面加上延时变量SETLOCAL ENABLEDELAYEDEXPANSION
延时间隔语句为choice /t 60 /d y /n >nul
。下面的批处理作用就是每隔60秒获取一次tcp连接数,并写入txt文件。
- @echo off
- ::启用变量延迟 !variable!
- SETLOCAL ENABLEDELAYEDEXPANSION
- echo 监控日期:%date:~0,10%>>TCP.txt
- ::intervalTime间隔时间(秒)
- set intervalTime=60
- :start
- ::if循环300次,每次间隔intervalTime秒
- set /a n+=1
- if %n% leq 300 (
-
- ::每个批处理命令结果赋值给变量
- for /F %%i in ('netstat -ano ^|find /i /c "TIME_WAIT"') do ( set tcp1=%%i)
- for /F %%i in ('netstat -ano ^|find /i /c "ESTABLISHED"') do ( set tcp2=%%i)
- for /F %%i in ('netstat -ano ^|find /i /c "LISTENING"') do ( set tcp3=%%i)
- :: ^|为转义,将上面3个cmd的命令结果写入到txt文件中
- echo Time:%time:~0,2%:%time:~3,2%:%time:~6,2%^|TCP_TIME_WAIT:!tcp1!^|TCP_ESTABLISHED:!tcp2!^|TCP_LISTENING:!tcp3! >> TCP.txt
- ::间隔时间
- choice /t %intervalTime% /d y /n >nul
- goto :start)
运行效果图:
另一种写法:
- @echo off
- ::启用变量延迟
- SETLOCAL ENABLEDELAYEDEXPANSION
- echo 监控日期:%date:~0,10%>>TCP.txt
- ::intervalTime间隔时间(秒)
- set intervalTime=3
- :start
- ::if循环300次,每次间隔intervalTime秒
- set /a n+=1
- if %n% leq 300 (
- choice /t %intervalTime% /d y /n >nul
- echo %time:~0,2%:%time:~3,2%:%time:~6,2% >> TCP.txt
- ::不换行将TCP的TIME_WAIT:XX写入到TCP.txt
- set /p=" TCP_TIME_WAIT:"
> TCP.txt - netstat -ano |find /i /c "TIME_WAIT" >> TCP.txt
- ::不换行将TCP的ESTABLISHED:XX写入到TCP.txt
- set /p=" TCP_ESTABLISHED:"
> TCP.txt - netstat -ano |find /i /c "ESTABLISHED" >> TCP.txt
- ::不换行将TCP的LISTENING:XX写入到TCP.txt
- set /p=" TCP_LISTENING:"
> TCP.txt - netstat -ano |find /i /c "LISTENING" >> TCP.txt
- goto :start)