VB script to get IP address from Ping command - vbscript

I'm trying to write a script to show every server ipaddress that I put into a text file. I've been looking online and came across the script below. What I need is instead of it showing 'online' I need it show show the actual IP address of each server in the text file. I've been looking for an answer to this for a while now, I've pretty new to vbs so I'm sorry if the script below is wrong or simple. This does open an excel doc which I'm pretty happy with.
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

Edited because my original statement wasn't accurate. You can get the StdOut of a process launched with exec like this:
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
However, the exec function has no WindowStyle option, so you'll see the command processor flash up for every time it runs ping.

You can use the RUN method of the script shell instead and have the ping statement output to a text file. Then read the text file once the ping statement completes and get the info that way.
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
Or something along those line. That should get you on the right track.

Related

Got error object required when connecting WMI

I want to create an Excel log file to record the hostname, IP, status of ping and the status of a WMI connection. When I try to run the script I've got an error "object required", but when I check the code I couldn't find where I should change the code.
On Error Resume Next
Set Fso = CreateObject("Scripting.FileSystemObject")
Set InputFile = Fso.OpenTextFile("file.txt", 1)
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
objExcel.Workbooks.Add
intRow = 2
objExcel.Cells(1, 1).Value = "Hostname"
objExcel.Cells(1, 2).Value = "IP"
objExcel.Cells(1, 3).Value = "Ping"
objExcel.Cells(1, 4).Value = "WMI"
Do While Not (InputFile.atEndOfStream)
hostname = InputFile.ReadLine
Set WshShell = CreateObject("WScript.Shell")
Set Ping = WshShell.Run("ping -n 1 " & hostname, 0, True)
objExcel.Cells(intRow, 1).Value = hostname
Select Case Ping
Case 0 objExcel.Cells(intRow, 3).Value = "On Line"
Case 1 objExcel.Cells(intRow, 3).Value = "Off Line"
Case 2 objExcel.Cells(intRow, 3).Value = "N/A"
End Select
Set objWMI = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & hostname & "\root\cimv2")
Set IPconfig = objWMI.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
If Err.Number = 0 Then
objExcel.Cells(intRow, 4).Value = "Pass"
For Each IP In IPconfig
If Not IsNull(IP.IPAddress) Then
For i = LBound(IP.IPAddress) To UBound(IP.IPAddress)
objExcel.Cells(intRow, 2).Value = IP.IPAddress(i)
Next
Else
objExcel.Cells(intRow, 2).Value = "N/A"
End If
Next
Else
objExcel.Cells(intRow, 4).Value = Err.Description
End If
intRow = intRow + 1
Loop
objExcel.Range("A1:B1:C1:D1").Select
objExcel.Selection.Interior.ColorIndex = 19
objExcel.Selection.Font.ColorIndex = 11
objExcel.Selection.Font.Bold = True
objExcel.Cells.EntireColumn.AutoFit
InputFile.Close
On Error Goto 0
Set objExcel = Nothing
Set Fso = Nothing
Set InputFile = Nothing
Set objWMIService = Nothing
Set WshShell = Nothing
Set Ping = Nothing
Set IPconfig = Nothing
MsgBox "Done Analyse"
objExcel.Quit
Wscript.Quit
Set Ping = WshShell.Run("ping -n 1 " & hostname, 0, True)
WshShell returns an integer not an object. Set is ONLY user for objects. So just delete set word.
Wmi can do it's own pinging. Here's the command line version but you can plug it in to the WMI statement you are using for NetworkAdaptor.
wmic /append:"textfile.txt" path win32_pingstatus where "address='127.0.0.1' and responsetime > 100" get responsetime,timestamprecord
For help that is same as vbscript type wmic path win32_pingstatus get /?

Pinging and launching program

I am trying to make a script which pings an IP address until it receives a response. When it does, it launches another script called "sound.vbs". I've got 2 issues:
I don't
want the cmd window to pop up when ping command is executed.
Even when ping fails, script simply shuts down instead of waiting some time and retrying the ping.
Code:
Dim objShell
Set objShell = Wscript.CreateObject("WScript.Shell")
Dim target 'define target ip
Dim result 'define ping result
target= "193.105.173.130" 'Archeage EU server IP (possibly Shatigon)
result = "Request timed out" 'Initial result
Set shell = WScript.CreateObject("WScript.Shell") 'create WScript shell
Set shellexec = shell.Exec("ping " & target) 'setting up the ping
Dim count
count = 1
Do
result = LCase(shellexec.StdOut.ReadAll)
If InStr(result , "reply from") Then
objShell.Run "sound.vbs"
Set objShell = Nothing
count = count + 1
Else
WScript.Sleep 4000
End If
Loop until count < 2
How do I solve the listed issues?
You can try like this script just modify to yours :
Option Explicit
Dim strComputer,objPing,objStatus
strComputer = "smtp.gmail.com"
Set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}!\\").ExecQuery _
("select * from Win32_PingStatus where address = '" & strComputer & "'")
For Each objStatus in objPing
If objStatus.Statuscode = 0 Then
Call MyProgram()
wscript.quit
End If
Next
'****************************************************
Sub MyProgram()
Dim objShell
Set objShell = CreateObject( "WScript.Shell" )
objShell.Run("calc.exe")
Set objShell = Nothing
End Sub
'****************************************************
Inspired from Loop a function?
If StrComp(right(WScript.FullName,11),"wscript.exe",1) = 0 Then '' hide the popup of cmd windows
WScript.Quit CreateObject("WScript.Shell").Run("cscript.exe //nologo """ & WScript.ScriptFullName & """", 0, False)
End If
Dim target 'define target ip
Dim result 'define ping result
target= "8.8.8.8" 'Archeage EU server IP (possibly Shatigon)
result = "Request timed out" 'Initial result
Dim Shell
Set Shell = WScript.CreateObject("WScript.Shell") 'create WScript shell
Dim count
count = 1
Do
Set shellexec = Shell.Exec("ping " & target) 'setting up the ping
result = LCase(shellexec.StdOut.ReadAll)
If InStr(1,result , "TTL=",1)> 0 Then
Shell.Run "sound.vbs",0,False
Exit Do
Else
WScript.Sleep 4000
count = count + 1
End If
Loop Until count > 2
Set Shell = Nothing
WScript.Quit
1-The first 3 line of code hide the popup of command line windows
2-exec the ping command have to done inside do loop not out so you will have second retry if first ping fail
3- Use TTL= instead of replay from (localhost or router can send replay from while target not reachable )
4- until > 2 not less than (infinity loop)

Vbscript to ping a list of machines and check if the IP-Addresses has changed and if they have changed send a Mail

I search for a Script that pings a List of machines and if a IP has changed send a warning mail. Hope somebody can help me.
Greets Mohrjon
Is the ping sufficient information to know that the IP address has changed? - what if the network goes down for a short period of time whilst the script is running?
Anyhow these are three subs i have which i have bodged together which should do what you need
Firstly i would iterate through a text file (csv) to get my ip address, and in this case the name and email
Sub Open_Master_File()
Do While objTextFile.AtEndOfStream <> True
strLine = objTextFile.ReadLine
'skip if comment line found
If inStr(1,strLine, "'") Then
ElseIf inStr(1,strLine, ",") Then
arrayMasterFile = split(strLine, ",")
strStoreName = arrayMasterFile(0)
strComputerIP = arrayMasterFile(1)
strEmailRecipient = arrayMasterFile(2)
'Call ping function to check for online/offline computers
Call Ping_Computer()
End If
Loop
'Release Memory
objTextFile.Close()
Set objTextFile = Nothing
Set objMasterFSO = Nothing
End Sub
next i ping to each of the ip's (btw this will only show if the ip is offline, can you guarantee that the ip is online all of the time?)
Sub Ping_Computer()
Set wshShell = CreateObject("WScript.Shell")
'Run the ping program 3 times, with a 2000ms delay on each, 0 = don't display cmd prompt
'All three pings must be successful for CBool = true
pingSuccessful = Not CBool(wshShell.run("ping -n 3 -w 2000 " & strComputerIP,0,True))
If pingSuccessful = True Then
Else
Call Send_EMail()
End If
'Release memory
Set wshShell = Nothing
End Sub
Send an email
Sub Send_Email()
Set objEmail = CreateObject("CDO.Message")
strSubject = ""
strEmailFrom = ""
strBody = ""
objEmail.Subject = strSubject
objEmail.From = strEmailFrom
objEmail.To = strEmailRecipient
'Use Microsoft schemas for emails
objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = cdoNTLM
objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = strServer
objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = cMailPort
objEmail.Configuration.Fields.Update
objEmail.Textbody = strBody
'Check if an error occurs during the send email process, do not stop program
On Error Resume Next
objEmail.Send
'error on send
If Err.Number <> 0 Then
Else
End If
'clear errors
On Error Goto 0
'Release Memory
Set objEmail = Nothing
End Sub

Where is the variable to tell the script where the text file is located?

I have this script but cannot figure out for the life of me how to use it. In powershell I would just set the location of the file as
`$location = get-content (c:\folder\servers.txt)`
But I cannot figure out how to read in a text file through VBscript.
All I want to do is install an app on a list of servers :(
Here is the error I am getting
test.vbs(6, 9) Microsoft VBScript runtime error: Object required: 'objMasterVariablesFile'
strUser = ""
strPassword = ""
strMSI = ""
'load and read from a text file
Do While objMasterVariablesFile.AtEndOfStream <> True
strLine = objMasterVariablesFile.ReadLine
'skip if ' found at start of line, to allow for comment lines
If inStr(1, strLine, "'") Then
Else
servername = strLine
'install code here
Const wbemImpersonationLevelDelegate = 4
Set objWbemLocator = CreateObject("WbemScripting.SWbemLocator")
Set objConnection = objwbemLocator.ConnectServer _
(servername, "root\cimv2", strUser, strPassword)
objConnection.Security_.ImpersonationLevel = wbemImpersonationLevelDelegate
Set objSoftware = objConnection.Get("Win32_Product")
errReturn = objSoftware.Install(strMSI,,True)
End If
Loop

VBS Run cmd.exe output to a variable; not text file

This is what I have so far. It works; outputing the folder path to temp to a text file.
What I really want, is to output the data to a variable. Every example I see online, show how to do this using something like:
set objScriptExec = wshShell.Exec (strCommand)
followed by
strresult = LCase(objScriptExec.StdOut.ReadAll. // code
I want this to run with Run, not Exec, because I want the command prompt windows to be hidden as I will performing many commands with the code below. How can I capture that output to a variable?
Set wsShell = CreateObject("WScript.Shell")
strCommand = "cmd /c echo %temp% > %temp%\test.txt"
wsShell.Run strcommand,0,True
This may be done with the Windows Script Host Exec command. StdOut, StdIn, and StdErr may all be accessed, and ERRORLEVEL is available when the command completes.
Dim strMessage, strScript, strStdErr, strStdOut
Dim oExec, oWshShell, intErrorLevel
Dim ComSpec
Set oWshShell = CreateObject("WScript.Shell")
ComSpec = oWshShell.ExpandEnvironmentStrings("%comspec%")
intErrorLevel = 0
strScript = ComSpec & " /C echo %temp%"
On Error Resume Next
Set oExec = oWshShell.Exec (strScript)
If (Err.Number <> 0) Then
strMessage = "Error: " & Err.Message
intErrorLevel = 1
Else
Do While oExec.Status = 0
Do While Not oExec.StdOut.AtEndOfStream
strStdOut = strStdOut & oExec.StdOut.ReadLine & vbCrLf
Loop
Do While Not oExec.StdErr.AtEndOfStream
strStdErr = strStdErr & oExec.StdErr.ReadLine & vbCrLf
Loop
WScript.Sleep 0
Loop
intErrorLevel = oExec.ExitCode
strMessage = strStdOut & strStdErr & CStr(intErrorLevel)
End If
WScript.Echo (strMessage)
NOTE: Replacing "ReadLine" above with "Read(1)" accomplishes the same thing, but adds an ability to process characters rather than whole lines.
Of course Wscript.Shell would be a lot easier, but, since you want more fine grain control of your session, consider using Win32_Process. Usually, one uses this to control the placement of a new window, but, in your case, you want it hidden, so I set startupInfo.ShowWindow = 0 which means SW_HIDE. The following declares a VBScript function called RunCmd and which will run a command in an invisible window saving the output to a text file and then return the contents of the text file to the caller. As an example, I invoke RunCmd with the HOSTNAME command:
Function RunCmd(strCmd)
Dim wmiService
Set wmiService = GetObject("winmgmts:\\.\root\cimv2")
Dim startupInfo
Set startupInfo = wmiService.Get("Win32_ProcessStartup")
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
Dim cwd
cwd = fso.GetAbsolutePathname(".")
startupInfo.SpawnInstance_
startupInfo.ShowWindow = 0
' startupInfo.X = 50
' startupInfo.y = 50
' startupInfo.XSize = 150
' startupInfo.YSize = 50
' startupInfo.Title = "Hello"
' startupInfo.XCountChars = 36
' startupInfo.YCountChars = 1
Dim objNewProcess
Set objNewProcess = wmiService.Get("Win32_Process")
Dim intPID
Dim errRtn
errRtn = objNewProcess.Create("cmd.exe /c """ & strCmd & """ > out.txt", cwd, startupInfo, intPID)
Dim f
Set f = fso.OpenTextFile("out.txt", 1)
RunCmd = f.ReadAll
f.Close
End Function
MsgBox RunCmd("HOSTNAME")
References:
Create method of the Win32_Process class
Win32_ProcessStartup class

Resources