我有一个批处理文件,如果ip地址已链接(ping成功),则应该回显链接为up
,如果不是,则回显链接为down
,由于某种原因我输入在命令提示符
checklink 192.168.0.238
这不是链接地址(假设获得down
信号),我先获得up
然后我得到正确的信号down
输出是:
link is up
link is down
这是批处理文件:
@setlocal enableextensions enabledelayedexpansion
@echo off
REM checking the state of the current ip addres
set ipaddr=%1
set oldstate=neither
:loop
set state=up
ping -n 1 !ipaddr! >nul: 2>nul:
if not !errorlevel!==0 set state=down
if not !state!==!oldstate! (
echo.Link is !state!
set oldstate=!state!
)
ping -n 2 127.0.0.1 >nul: 2>nul:
goto :loop
endlocal
我的问题为什么它最初不起作用然后才开始工作?
答案 0 :(得分:1)
作为上述评论的延续,errorlevel
不能被视为真正的指标,因为ping返回时如何设置ping是否有效Destination host unreachable.
以下是我的意思的一个例子:
c:\>ping -n 1 192.168.0.238&echo ERRORLEVEL = !errorlevel!
Pinging 192.168.0.238 with 32 bytes of data:
Request timed out.
Ping statistics for 192.168.0.238:
Packets: Sent = 1, Received = 0, Lost = 1 (100% loss),
ERRORLEVEL = 1
c:\>ping -n 1 192.168.0.238&echo ERRORLEVEL = !errorlevel!
Pinging 192.168.0.238 with 32 bytes of data:
Reply from x.x.x.x: Destination host unreachable.
Ping statistics for 192.168.0.238:
Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
ERRORLEVEL = 0
c:\>ping -n 1 192.168.0.238&echo ERRORLEVEL = !errorlevel!
Pinging 192.168.0.238 with 32 bytes of data:
Request timed out.
Ping statistics for 192.168.0.238:
Packets: Sent = 1, Received = 0, Lost = 1 (100% loss),
ERRORLEVEL = 1
此代码似乎工作得更好:
@echo off
setlocal enableextensions enabledelayedexpansion
REM checking the state of the current ip addres
set ipaddr=%1
set oldstate=neither
:loop
set state=down
for /f "skip=2 tokens=6 delims= " %%i in ('ping -n 1 !ipaddr!') do if "%%i"=="TTL=128" set state=up
if not !state!==!oldstate! (
echo.Link is !state!
set oldstate=!state!
)
ping -n 2 127.0.0.1 >nul: 2>nul:
goto :loop
endlocal
当我运行checklink 192.168.0.238
时,我得到link is down
并且它永远不会切换到up
。当我运行checklink 127.0.0.1
时,我得到link is up
。
答案 1 :(得分:1)
试试这个:
@echo off
setlocal
set IPaddy=%~1
:loop
Call :IsPingable %IPaddy% && (echo %IPaddy% is up & exit /b) || (echo %IPaddy% is down & goto :loop)
:IsPingable <comp>
ping -n 1 -w 3000 -4 -l 8 "%~1" | Find "TTL=">nul
exit /b
答案 2 :(得分:0)
脚本已更新,以显示发生更改并使用任何TTL值的当前日期和时间
(看起来原始脚本checklink.cmd
来自another stackoverflow post)。
注意:使用bytes=50
的建议不适用于所有地区。
@echo off
setlocal enableextensions enabledelayedexpansion
REM checking the state of the current ip address
set ipaddr=%1
set oldstate=neither
if x!ipaddr!==x (
echo Missing ip address argument
goto :end
)
:loop
set state=down
for /f "skip=2 tokens=6" %%i in ('ping -n 1 !ipaddr!') do (
set ttl=%%i
set removedttl=!ttl:TTL=!
if not x!ttl!==x!removedttl! set state=up
)
if not !state!==!oldstate! (
echo.Link is !state! at %date% %time:~0,2%:%time:~3,2%:%time:~6,2%
set oldstate=!state!
)
ping -n 2 127.0.0.1 >nul: 2>nul:
goto :loop
:end
endlocal