VB脚本从Ping命令获取IP地址

时间:2014-02-05 10:03:44

标签: vbscript show

我正在尝试编写一个脚本来显示我放入文本文件的每个服务器ipaddress。我一直在网上看到并且遇到了下面的脚本。我需要的是它而不是显示'在线'我需要它显示文本文件中显示每个服务器的实际IP地址。我一直在寻找这个问题的答案,我对vbs很新,所以如果下面的脚本错误或简单,我很抱歉。这确实打开了一个我非常满意的Excel文档。

Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
objExcel.Workbooks.Add
intRow = 2

objExcel.Cells(1, 1).Value = "Server Name"
objExcel.Cells(1, 2).Value = "IP Address"

Set Fso = CreateObject("Scripting.FileSystemObject")
Set InputFile = fso.OpenTextFile("MachineList.Txt")

Do While Not (InputFile.atEndOfStream)
HostName = InputFile.ReadLine

Set WshShell = WScript.CreateObject("WScript.Shell")
Ping = WshShell.Run("ping -n 1 " & HostName, 0, True)

objExcel.Cells(intRow, 1).Value = HostName

Select Case Ping
Case 0 objExcel.Cells(intRow, 2).Value = "On Line"
Case 1 objExcel.Cells(intRow, 2).Value = "Off Line"
End Select

intRow = intRow + 1
Loop

objExcel.Range("A1:B1").Select
objExcel.Selection.Interior.ColorIndex = 19
objExcel.Selection.Font.ColorIndex = 11
objExcel.Selection.Font.Bold = True
objExcel.Cells.EntireColumn.AutoFit 

2 个答案:

答案 0 :(得分:0)

编辑因为我的原始陈述不准确。您可以获取使用exec启动的流程的StdOut,如下所示:

Option Explicit

Const HOST_FILE = "MachineList.txt"

Dim shl, exe, exl, fso, file
Dim iRow, out, host

Set shl = CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FilesystemObject")
Set exl = CreateObject("Excel.Application")

exl.Workbooks.Add
iRow = 2
exl.Cells(1,1).Value = "Server Name"
exl.Cells(1,2).Value = "IP Address"

Set file = fso.OpenTextFile(HOST_FILE)

While not file.AtEndOfStream
  host = Trim(file.ReadLine)

  exl.Cells(iRow,1).Value = host  

  Set exe = shl.Exec("%COMSPEC% /c ping -n 1 """ & host & """ | Find ""statistics for""")

  If Not exe.StdOut.AtEndOfStream Then
    out = exe.StdOut.ReadAll
    exl.Cells(iRow,2).Value = getIP(out)
  Else
    exl.Cells(iRow,2).Value = "Ping Failed"
  End If  

  iRow = iRow + 1
Wend

exl.Visible = True
Set exl = Nothing
Set shl = Nothing
Set fso = Nothing
Set exe = Nothing
WScript.Quit

Function getIP(text)
  Dim s

  s = Mid(text, Len("Ping statistics for ") + 1)
  getIP = Trim(Replace(s,":",""))
End Function

但是,exec函数没有WindowStyle选项,因此您每次运行ping时都会看到命令处理器闪烁。

答案 1 :(得分:0)

您可以使用脚本shell的RUN方法,并将ping语句输出到文本文件。然后在ping语句完成后读取文本文件并以此方式获取信息。

Set objWSH = CreateObject("WScript.Shell")
objWSH.Run "%COMSPEC% /c ping -n 1 """ & host & """ | Find ""statistics for"" > temp.txt", 0, True
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("temp.txt", 1)
out = Trim(objFile.ReadAll)
If out <> "" Then
    ' Read ping data
Else
    ' Ping failed to run
End If

或者那些东西。这应该会让你走上正轨。