批处理文件检查IP地址状态

问题描述 投票:0回答:3

我有一个批处理文件,如果ip地址被链接(ping成功),则应该回显链接是up,如果不是,则echo链接是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

我的问题为什么它最初不起作用然后它开始工作?

batch-file networking ip
3个回答
1
投票

作为上述评论的延续,errorlevel不能被信任作为一个真正的指标,因为当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
投票

试试这个:

@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

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
© www.soinside.com 2019 - 2024. All rights reserved.