簡體   English   中英

將名稱添加到 IP 地址而不使批處理文件失敗

[英]Adding names to an IP address without failing the batch file

我想使用批處理文件來 ping 一組服務器。 批處理文件工作並報告正常或失敗。 我想要的只是讓它在支票中顯示服務器的名稱。

這是我在批處理文件中使用的:

@echo off
for /f "delims=" %%a in (C:\List of IPs.txt) do ping -n 1 %%a >nul && (echo %%a ok) || (echo %%a failed to respond) 
pause

在它指向的文本文件中只是一個 IP 列表,我如何制作它以便我可以在 IP 旁邊看到一個名稱? 先感謝您!

只需插入另一個for /f循環來獲取名稱:

@echo off
SetLocal 
for /f "usebackq" %%a in ("List of IPs.txt") do (
  for /f %%b in ('"ping -n 1 %%a >nul && (echo ok) || (echo failed to respond) "') do (
    for /f "tokens=1*" %%m in ('nslookup %%a  ^|findstr /b "Name:"') do (
     echo %%a   %%n %%b
    )
  )
)

一種選擇是將文件格式化為具有 IP 和您感興趣的名稱。

192.168.1.200 server1
192.168.1.201 server2
192.168.1.202 printer1
192.168.1.203 that one stupid printer in the back

然后你可以從文件中讀取兩者。 我要注意一件事——您檢查 ping 的方法並不一致。 即使 ping 實際失敗(來自“無法訪問”的有效響應),您也可以獲得錯誤級別 0。 相反(英文)成功的 ping 總是包含“ttl=”。 因此你會這樣做:

未經測試

@echo off
for /f "usebackq tokens=1* delims= " %%a in ("C:\List of IPs.txt") do ping -n 1 %%a ^|find /i "ttl=" >nul && (echo %%b at %%a is ok) || (echo %%b at %%a failed to respond)
pause

如果您有 dns 可以處理您嘗試訪問的所有內容,則可以利用 nslookup 和/或 ping -a。

根據評論,我添加了以下解決方案,適用於我的英語 Windows 10 計算機,上面的文本文件:

@echo off
for /f "usebackq tokens=1* delims= " %%a in ("C:\temp\List of IPs.txt") do ping -n 1 -w 1500 %%a |find /i "ttl=" >nul &&echo %%b at %%a is ok||echo %%b at %%a failed to respond
pause

請注意,在delims= "處的等號和雙引號之間有一個空格

Output:

server1 at 192.168.1.200 is ok
server2 at 192.168.1.201 is ok
printer1 at 192.168.1.202 is ok
that one stupid printer in the back at 192.168.1.203 failed to respond
Press any key to continue . . .

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM