检测批处理IP冲突
问题描述:
如何检测IP冲突?检测批处理IP冲突
我试图实现两个系统的故障切换。让我们假设他们采用IP X.X.X.1和X.X.X.2(为了方便起见,A和B),A作为主服务器,B作为备份。
A和B都会连续ping X.X.X.1。应该在不断下降,B将检测“请求超时”,并使用以下命令将其转换到X.X.X.1:
netsh int ipv4 set address name="Local Area Connection" source=static address=X.X.X.1 mask=255.255.255.0 gateway=none
当A重新连接本身,我想故障切换,从而平稳且自动发生。现在,由于有两台X.X.X.1的机器,所以会出现IP冲突。 B保留X.X.X.1,而作为“后来”计算机的A将收到此冲突。当A试图再次ping通X.X.X.1,A而不是接收:然后
PING: General failure.
一个会以某种方式检测到,并自己转化为X.X.X.2。现在两台机器都运行良好,只是它们镜像成像。
或者这就是逻辑。目前,我无法检测到PING:一般故障。如何去做这件事?
或者如果有更好的方法来做故障切换,它会是什么?
答
我认为在测试错误之前,您需要将ping
命令的stderr重定向到标准输出2>&1
。
:loop
ping x.x.x.1 2>&1 | find /i "general failure" && (
netsh int ipv4 set address name="Local Area Connection" source=static address=X.X.X.2 mask=255.255.255.0 gateway=none
)
goto loop
它可能会更好地检查成功,而不是失败。这里有一些更强大的应该从1.2开始,如果.1死亡则从.1开始;如果冲突则从.1到.2。
@echo off
setlocal
:: Host to ping
set primary=x.x.x.1
:: Ping with options (1 ping sent per loop, wait 500 ms for timeout)
set ping_options=-n 1 -w 500
:: Fail over after x ping failed responses
set fail_limit=5
:loop
:: Ping x.x.x.1. Test for "reply from". If success, set failures=0; otherwise, increment failures
(ping %ping_options% %primary% 2>&1 | find /i "reply from" >NUL && set failures=0) || set /a "failures+=1"
:: If failures >= limit, switch IP
if failures GEQ %fail_limit% call :switch
:: Pause for a second and begin again.
ping -n 2 0.0.0.0 >NUL
goto loop
:: Switch subroutine
:switch
:: Get current IPv4 address
for /f "tokens=2 delims={}," %%I in ('wmic nicconfig where ipenabled="TRUE" get ipaddress /format:list') do set IP=%%~I
:: If the last character if the current IP is 1, switch to 2 (or vice versa)
if %IP:~-1%==1 (set other=%IP:0,-1%2) else set other=%IP:0,-1%1
:: Perform the switch
netsh int ipv4 set address name="Local Area Connection" source=static address=%other% mask=255.255.255.0 gateway=none
答
批量流水线,或许
ping ..whateveryou'dusetogeneratetheerror.. X.X.X.1 |find /i "General failure" >nul
if not errorlevel 1 netsh...(as above)
你的先生,是一大福音。感谢您的快速回复和详细的回复,我会尝试一下并让您知道。谢谢! :) – Wakka02 2013-03-18 18:38:10
@ Wakka02 - 我只是碰巧认为循环可能需要暂停,所以它不会icmp炸毁您的主服务器。我只是暂停更新我的代码(ping到故意错误的0.0.0.0)。不要修改'0.0.0.0',而是**修改'X.X.X.1'。 – rojo 2013-03-18 18:52:45