1. 程式人生 > >Windows下bat腳本判斷端口是否可用

Windows下bat腳本判斷端口是否可用

bat telnet


環境:

一臺服務器上用了portmap做了端口轉發,但是這個程序經常會跪,需要人工去重啟

解決思路:

通過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.6\PortMap.exe") else (taskkill /F -IM PortMap.exe & start "" "D:\PortMap1.6\PortMap.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.6\PortMap.exe") else (taskkill /F -IM PortMap.exe & start "" "D:\PortMap1.6\PortMap.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


本文出自 “我本不是菜鳥” 博客,請務必保留此出處http://ityunwei2017.blog.51cto.com/7662323/1924966

Windows下bat腳本判斷端口是否可用