0

我正在尝试 ping 大约 20-30 个文本文件上的服务器,并且可以相应地更新(服务器不断更改名称或变得过时)。而且我不想将服务器放在批处理文件中,并且每次发生更改时都必须对其进行编辑。

但我的问题是:如何从 .t​​xt 文件中 ping 一组服务器,并在单独的 .txt 文件(我们称之为“Site_A_Servers.txt”)上输出结果(如果它在线或不在线):

Site_A_Servers.txt:
Server A is online.
Server B is online.
Server C is offline!
Server D is etc..

感谢您的时间!:)

4

3 回答 3

5

这使用 ping.exe 设置的错误级别

@echo off
del log.txt 2>nul
for /f "delims=" %%a in (servers.txt) do ping -n 2 %%a >nul && ( 
>>log.txt echo server %%a is online&echo %%a online) || ( 
>>log.txt echo server %%a is OFFLINE&echo %%a OFFLINE)
于 2013-06-04T06:40:01.923 回答
3
@echo off
(for /F "delims=" %%a in (ServersList.txt) do (
   for /F %%b in ('ping -n 1 "%%a" ^| find /I "TTL="') do set reply=%%b
   if defined reply (
      echo Server %%a is online.
   ) else (
      echo Server %%a is offline!
   )
)) > Site_A_Servers.txt

编辑添加了新版本。

下面的版本使用ping命令返回的 ERRORLEVEL,正如 Joey 所建议的那样。

@echo off
setlocal EnableDelayedExpansion
(for /F "delims=" %%a in (ServersList.txt) do (
   ping -n 1 "%%a" > NUL
   if !errorlevel! equ 0 (
      echo Server %%a is online.
   ) else (
      echo Server %%a is offline!
   )
)) > Site_A_Servers.txt
于 2013-06-04T03:03:53.177 回答
1

您可以编写一个 VB 脚本来执行此操作。

Set objFS = CreateObject("Scripting.FileSystemObject")
strFile = "c:\test\ipList.txt"
strTemp = "c:\test\ip_testOP.txt"
Set objFile = objFS.OpenTextFile(strFile)
Set objOutFile = objFS.CreateTextFile(strTemp,True)    
Do Until objFile.AtEndOfStream
    strLine = objFile.ReadLine

    objOutFile.Writeln(Ping(strLine))
Loop
objOutFile.Close
objFile.Close
objFS.DeleteFile(strFile)
objFS.MoveFile strTemp,strFile 


Function Ping(strHost)
    Dim oPing, oRetStatus, bReturn
    Set oPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery("select * from Win32_PingStatus where address='" & strHost & "'")

    For Each oRetStatus In oPing
        If IsNull(oRetStatus.StatusCode) Or oRetStatus.StatusCode <> 0 Then
            bReturn = False

            ' WScript.Echo "Status code is " & oRetStatus.StatusCode
        Else
            bReturn = True

            ' Wscript.Echo "Bytes = " & vbTab & oRetStatus.BufferSize
            ' Wscript.Echo "Time (ms) = " & vbTab & oRetStatus.ResponseTime
            ' Wscript.Echo "TTL (s) = " & vbTab & oRetStatus.ResponseTimeToLive
        End If
        Set oRetStatus = Nothing
    Next
    Set oPing = Nothing

    Ping = bReturn
End Function

资料来源:

http://larsmichelsen.com/vbs/quickie-how-to-ping-a-host-in-vbs-i-got-two-ways/

使用 VBScript 读取和写入文件

于 2013-06-04T01:09:10.380 回答