Windows下bat脚本判断端口是否可用

环境:

解决思路:

通过bat来监控程序端口,不通时候自动重启,如果端口可用,则会出来telnet进程,若端口不可用,则不会出现telnet进程。根据进程是否存在来判断端口是否可用,因为telnet通的话,会直接跳转窗口,无回显,所以需要telnet时候启用新窗口。

方法二

@echo off
title PortMap存活监控!!!
:again
set ip=127.0.0.1
set port=8080
start telnet.exe %ip% %port%
ping -7 127.0.0.1 > null
tasklist|findstr /i "telnet.exe" > nul
if ERRORLEVEL 1 (goto err) else (goto ok)

:err
tasklist|findstr -i "portmap.exe"
if ERRORLEVEL 1 (start "" "D:PortMap1.6PortMap.exe") else (taskkill /F -IM PortMap.exe & start "" "D:PortMap1.6PortMap.exe")

:ok
taskkill /F -IM "telnet.exe" >> nul
echo PortMap Services is running %Date:~0,4%-%Date:~5,2%-%Date:~8,2% %Time:~0,2%:%Time:~3,2%

ping -n 300 127.0.0.1 >nul
goto again

方法二

@echo off
title PortMap存活监控!!!
:again
set ip=127.0.0.1
set port=8080
netstat -ano|findstr %ip%:%port%|findstr -i ESTABLISHED
if ERRORLEVEL 1 (goto err) else (goto ok)

:err
tasklist|findstr -i "portmap.exe"
if ERRORLEVEL 1 (start "" "D:PortMap1.6PortMap.exe") else (taskkill /F -IM PortMap.exe & start "" "D:PortMap1.6PortMap.exe")

:ok
echo PortMap Services is running %Date:~0,4%-%Date:~5,2%-%Date:~8,2% %Time:~0,2%:%Time:~3,2%

ping -n 300 127.0.0.1 >nul
goto again
环境: 解决思路: 通过bat来监控程序端口,不通时候自动重启,如果端口可用,则会出来telnet进程,若端口不可用,则不会出现telnet进程。根据进程是否存在来判断端口是否可用,因为telnet通的话,会直接跳转窗口,无回显,所以需要telnet时候启用新窗口。 方法二 @echo off title PortMap存活监控!!! :again set ip=127.0.0.1 set port=8080 start telnet.exe %ip% %port% ping -7 127.0.0.1 > null tasklist|findstr /i "telnet.exe" > nul if ERRORLEVEL 1 (goto err) else (goto ok) :err tasklist|findstr -i "portmap.exe" if ERRORLEVEL 1 (start "" "D:PortMap1.6PortMap.exe") else (taskkill /F -IM PortMap.exe & start "" "D:PortMap1.6PortMap.exe") :ok taskkill /F -IM "telnet.exe" >> nul echo PortMap Services is running %Date:~0,4%-%Date:~5,2%-%Date:~8,2% %Time:~0,2%:%Time:~3,2% ping -n 300 127.0.0.1 >nul goto again 方法二 @echo off title PortMap存活监控!!! :again set ip=127.0.0.1 set port=8080 netstat -ano|findstr %ip%:%port%|findstr -i ESTABLISHED if ERRORLEVEL 1 (goto err) else (goto ok) :err tasklist|findstr -i "portmap.exe" if ERRORLEVEL 1 (start "" "D:PortMap1.6PortMap.exe") else (taskkill /F -IM PortMap.exe & start "" "D:PortMap1.6PortMap.exe") :ok echo PortMap Services is running %Date:~0,4%-%Date:~5,2%-%Date:~8,2% %Time:~0,2%:%Time:~3,2% ping -n 300 127.0.0.1 >nul goto again
经验分享 程序员 微信小程序 职场和发展