【问题标题】:Extracting IP from ping into variable in bat script从 ping 中提取 IP 到 bat 脚本中的变量中
【发布时间】:2013-06-10 18:01:36
【问题描述】:

有没有我可以做到这一点?

@echo off
REM #Testing FIND in IPCONFIG

setlocal EnableDelayedExpansion

for /f "tokens=3" %%a in ('ping localhost ^| findstr /i "reply"') do (
  set address=%%a
  set address=!address::=!
)

ipconfig /all | findstr %address%
if ERRORLEVEL = 1 goto VIP_NOT_FOUND

REM #We are here becuase the find returned a result.
REM #It is safe to execute the rest of the application.
REM #EXECUTES THE SCRIPT HERE

echo "testing works" >> testing.txt

:VIP_NOT_FOUND
REM #This part of the script is where you would handle any
REM #error logging or other admin related
echo "Could not find a VIP. - Exiting"
echo "end of script reached."

我在 windows server 2k8 ENG 版本上运行这个脚本。它似乎一直在给我 findstr : bad command line。但我不确定问题出在哪里。

【问题讨论】:

  • 你的批处理文件的最终目标是...?
  • @ShivanRaptor 我的批处理文件的最终目标是在当前服务器上将 ip 映射为辅助 ip 时运行脚本。
  • 检查%address% 的值。我怀疑它是未定义的,因为ping localhost 失败了。这是我能想到的唯一会导致 FINDSTR %address%` 命令失败的场景。

标签: windows batch-file cmd ip


【解决方案1】:

这样的事情应该可以工作:

@echo off

setlocal EnableDelayedExpansion

for /f "tokens=3" %%a in ('ping myhost.com ^| find /i "reply"') do (
  set address=%%a
  set address=!address:~0,-1!
)

ipconfig /all | findstr "%address%" >nul && (
  rem Do stuff
)

如果主机同时具有 IPv4 和 IPv6 地址,并且您正在寻找 IPv4 地址,请使用 ping -4 而不仅仅是 ping

【讨论】:

  • 如果我在字节中使用带有 /i 的 findstr,则会显示 findstr 错误:命令行错误。但是如果我使用你的代码,它会抛出一个找不到文件的错误。我在 windows server 2k8 上运行
  • 查看更新的答案。我将过滤器更改为reply(可能需要针对非英语版本进行调整)并修复了地址清理,使其不会阻塞 IPv6 地址。
猜你喜欢
  • 2012-10-19
  • 2021-10-23
  • 2011-06-10
  • 1970-01-01
  • 2019-02-26
  • 1970-01-01
  • 2014-03-01
  • 2016-07-09
相关资源
最近更新 更多