从文本文件Ping服务器

时间:2013-06-04 00:15:45

标签: file text batch-file ping

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

但我的询问是:如何从.txt文件中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..

感谢您的时间! :)

3 个答案:

答案 0 :(得分:5)

这使用ping.exe设置的errorlevel

@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)

答案 1 :(得分: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

答案 2 :(得分: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/

Read and write into a file using VBScript