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

问题描述 投票:0回答:2

我正在尝试编写一个脚本来显示我放入文本文件的每个服务器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 
vbscript show
2个回答
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时,您都会看到命令处理器闪烁。


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

或者沿着那条线的东西。这应该让你走上正轨。

© www.soinside.com 2019 - 2024. All rights reserved.