How to write a VBS Script to check a website and then stop and start a windows service - windows

I need to write a VBS script to check a website for certain text : "Service Unavailable" and "Error in /"
When it finds this I need it to restart the windows service "World wide publishing service"
Where do I start?
Any help would be much appreciated!
Cheers!
Andy

You can check on a web site by using the MSXML2.XMLHTTP object (ie the same object that internet explorer uses to fire AJAX requests) and checking the status code (200 is status OK, 404 is page not found etc)
dim http: set http = CreateObject("MSXML2.XMLHTTP")
http.open "GET", "http://site.com?param=value", false
http.send
if not http.status = 200 then
' something not right, start your service
end if
as far as starting a service is concerned, this page has quite a few examples of working with services, of which this is how to start one (copied verbatim, not tested):
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colServiceList = objWMIService.ExecQuery _
("Select * from Win32_Service where Name='NetDDE'")
For each objService in colServiceList
errReturn = objService.StartService()
Next
Wscript.Sleep 20000
Set colServiceList = objWMIService.ExecQuery("Associators of " _
& "{Win32_Service.Name='NetDDE'} Where " _
& "AssocClass=Win32_DependentService " & "Role=Dependent" )
For each objService in colServiceList
objService.StartService()
Next
if the service you want to start is IIS, then perhaps you dispense with the http request and instead directly detect whether the IIS service is running or not

Related

Select from Object with multiple attributes "Invalid query" Error

I have a Server with multiple Sessions on it, which all have to have a process running.
My Program should start up that process as soon as it stopped and the Session is online.
I checked for the process, and if I didn't find it I just started it. The problem is, I see the same process over all Sessions. How can I just get the processes of my Session and not the whole Server's?
This was my try, but it throws me an Error:
option explicit
DIM strComputer
DIM strProcessName
DIM WshShell
DIM strWMIQuery
DIM strSessionID
Set wshShell = CreateObject("WScript.Shell")
strSessionID= wshShell.ExpandEnvironmentStrings("%SESSIONID%")
strComputer = "."
strProcessName = "FortiSwitch-Replacer.exe"
strWMIQuery = "Select * from Win32_Process where name like '" & strProcessName & "' AND SessionId like '" & strSessionID & "'"
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
if objWMIService.ExecQuery(strWMIQuery).Count > 0 then
'Dont do anything
else
'start process
end if
The Error is at the "ExecQuery()" Part (line 18) saying "Invalid query"
Lankymart found out the Answer:
The SessionId needs to be an Integer while mine was a String. By Changing the Value into an Integer the program would've worked.
What I want to add:
The ExpandEnvironmentStrings don't offer the SessionId. Right now I've used a small script from an Answer of this Question: Is it possible to run Powershell code from VBScript?
It Runs the simple Powershell command to get the SessionId in VBS.
If anyone else has some different Ideas on how to get the SessionId another way I'm interested to learn and see them :)

Run BAT file on remote server using VBScript. No psexec, and as a different user

I'm trying to execute a a BAT file on a remote server using VBScript. Further requirements:
psexec is not allowed
I need the script to operate under the permissions of another user, not those of my own workstation
I have consulted this article: https://learn.microsoft.com/en-us/windows/desktop/WmiSdk/connecting-to-wmi-remotely-with-vbscript
I see how creating the connection works, but I can't figure out how to then create a process using that same connection.
I believe this solution is really close, the only problem is I think it impersonates the user of the computer it is currently running on:
strCommand = "C:\temp\copyall.bat"
strPath = "C:\temp"
strcomputer="."
process = "winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2"
msgbox process
Set objWMIService = GetObject(process)
Set objProcess = objWMIService.Get("Win32_Process")
errReturn = objProcess.Create(strCommand, strPath, Null, intProcessID)
If errReturn = 0 Then
WScript.Echo "scan success: " & intProcessID
Else
WScript.Echo "scan fail: " & errReturn
End If
This example from Microsoft's site shows how to create the connection properly but I don't know how to then use that connection.
' Full Computer Name
' can be found by right-clicking My Computer,
' then click Properties, then click the Computer Name tab)
' or use the computer's IP address
strComputer = "FullComputerName"
strDomain = "DOMAIN"
Wscript.StdOut.Write "Please enter your user name:"
strUser = Wscript.StdIn.ReadLine
Set objPassword = CreateObject("ScriptPW.Password")
Wscript.StdOut.Write "Please enter your password:"
strPassword = objPassword.GetPassword()
Set objSWbemLocator = CreateObject("WbemScripting.SWbemLocator")
Set objSWbemServices = objSWbemLocator.ConnectServer(strComputer, _
"Root\CIMv2", _
strUser, _
strPassword, _
"MS_409", _
"ntlmdomain:" + strDomain)
Set colSwbemObjectSet = objSWbemServices.ExecQuery("Select * From Win32_Process")
For Each objProcess in colSWbemObjectSet
Wscript.Echo "Process Name: " & objProcess.Name
Next
The answer is probably staring me in the face but I just can't see it right now. Ideas?
After connecting to the remote server simply get the Win32_Process object and call the Create() method like you'd do locally.
Set objSWbemServices = objSWbemLocator.ConnectServer(...)
Set objProcess = objSWbemServices.Get("Win32_Process")
errReturn = objProcess.Create(strCommand, strPath, Null, intProcessID)
The file you want to run must exist locally on the remote server for this to work.
Also note that this normally requires admin privileges on the remote system.

Clicked on this script from a SSD I bought second hand. Is it malicious?

I clicked without thinking and it didn't appear to do anything but shut the windows. Looking at the code I'm too noob to work out what it does but I'm paranoid it's done something behind the scenes.
Option Explicit
'On Error Resume Next
Dim strComputer
Dim objWmiService
Dim colMonitoredProcesses
Dim objLatestProcess
Dim colProcesses
Dim objProcess
strComputer = "."
Set objWmiService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
Set colProcesses = objWmiService.ExecQuery _
("Select * From Win32_Process Where Name = 'explorer.exe'")
For Each objProcess In colProcesses
objProcess.Terminate
Next
Set colMonitoredProcesses = objWmiService.ExecNotificationQuery _
("Select * From __InstanceCreationEvent " _
& "Within 1 Where TargetInstance Isa 'Win32_Process' " _
& "And (TargetInstance.Name = 'iexplore.exe' " _
& "Or TargetInstance.Name = 'notepad.exe')")
Do
Set objLatestProcess = _
colMonitoredProcesses.NextEvent.TargetInstance
If LCase(objLatestProcess.Name) = "iexplore.exe" Then
objLatestProcess.Terminate
End If
Loop
Looks like it might be some code that "waits for a process to start, terminates the process and exits when it sees a particular process start."
(Essentially, it just closes notepad and internet explorer processes, it seems)
Here's a link to a blog post on a Microsoft forum with almost exactly that code.
(Background vbscript that waits for a process to start, terminates the process and exits when it sees a patricular process start)
I think you are ok!
In the future don't click random stuff!
First it closes all explorer.exe instances (this is the Windows shell, basically taskbar and desktop). It then watches for Notepad or Internet Explorer to start and if it's Internet Explorer, shuts it down. Why it is also checking for Notepad to start but not doing anything, I don't know.

Need a VB Script to check if service exist

I want to write a VBS script which will check if specific service is installed/exist or not locally.
If it is not installed/exist, script will display message (any text) and disabled the network interface i.e. NIC.
If service exist and running, NO Action. Just exit.
If service exist but not running, same action, script will display message (any text) and disabled the network interface i.e. NIC.
i have below given code which is displaying a message in case one service is stop but it is not -
Checking if service exist or not
Disabling the NIC
strComputer = "."
Set objWMIService = Getobject("winmgmts:"_
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colRunningServices = onjWMIService.ExecQuery _
("select State from Win32_Service where Name = 'dhcp'")
For Each objService in colRunningServices
If objService.State <> "Running" Then
errReturn = msgbox ("Stopped")
End If
Next
Please help. Thanks in advance.
To know if service is installed, check colRunningServices.Count . It will be 0 if no service match the wmi query.
To disable NIC, use a wmi query SELECT * FROM Win32_NetworkAdapter, iterate de returned collection of NICs, find the one you are interested and use the Disable/Enable method of it. BUT this only will work if OS is Vista or later.
It would look something like this but I cannot test this!
Option Explicit
Const TITLE = "Title"
Const SERVICE = "dhcp"
Dim wmi
Dim svcs,svc
Set wmi = GetObject("winmgmts:\\.\root\cimv2")
Set svcs = wmi.ExecQuery("Select * from Win32_Service where Name = '" & SERVICE & "'")
If svcs.Count = 0 Then
Call MsgBox(SERVICE & " service does not exist",vbCritical,TITLE)
Call disableNIC(wmi)
Else
For Each svc In svcs
If svc.State <> "Running" Then
Call MsgBox(SERVICE & " service is not running",vbCritical,TITLE)
Call disableNIC(wmi)
End If
Next
End If
Set wmi = Nothing
WScript.Quit
Sub disableNIC(ByRef wmi)
Dim nics,nic
Set nics = wmi.ExecQuery("Select * from Win32_NetworkAdapter")
For Each nic In nics
nic.Disable
Next
End Sub
Beware that this disables every NIC. If you want to specify one you'd have to add a where clause in disableNIC. Also I imagine you would have to run this as an administrator.
Seems like a weird thing to want to do though...

Start Service with VBscript

I am trying to have this script take a text file running and stopped services before a reboot and start any services that did not automatically start after the machine starts back up. The script that gets the list of service names, state and startmode and creates a comma separated text file line by line works fine. Here it is for reference (taken from the interwebs, lost the link in my travels. Modified slightly.):
Const ForAppending = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objLogFile = objFSO.CreateTextFile("service_list.txt", _
ForWriting, True)
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colListOfServices = objWMIService.ExecQuery("Select * from Win32_Service")
For Each objService in colListOfServices
objLogFile.Write objService.Name & ","
objLogFile.Write objService.StartMode & ","
objLogFile.Write objService.State
objLogFile.Writeline
Next
objLogFile.Close
This next bit reads the file line by line, compares the state of all of the services with the state of the services that were recorded before the machine was shut down. If they match, do nothing, if they are different, start the service:
Const ForReading = 1
strComputer = "."
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set objServiceName = objWMIService.get("Win32_Service.Name='" & ServiceName & "'")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("\\some path\service_list.txt",ForReading,True,-2)
Do Until objFile.AtEndOfStream
fLine = Split(objFile.ReadLine,",")
'wscript.echo fLine(2)
if InStr(fLine(2),"Running") then
'wscript.echo "it was running!"
if objServiceName.Started then
'do nothing
else
'Set servicetostart = objWMIService.ExecQuery ("Select " & ServiceName & " from Win32_Service Where Name ='Alerter'")
'servicetostart.StartService()
'Result = objServiceName.StartService
'If 0 <> Result Then
' wscript.echo "Start " & ServiceName & " error:" & Result
'End If
objServiceName.StartService
'wscript.echo Servicename & "could not start with error: " & Result
end if
end if
'wscript.echo objServiceName
Loop
As of right now I am recieving an error whenever it actually tries to start the service. I receive a "Provider Failure code:80041004 Source:SWbemObjectEX". I have been looking through the posts about this error and attempting the fixes suggested. Also, as you can see, I have been trying variations, but I am afraid I am merely guessing.
So to my question, what is causing the "Provider Failure"? I have looked up these information for the Win32_Service Class here:
http://msdn.microsoft.com/en-us/library/windows/desktop/aa394418%28v=vs.85%29.aspx#methods
and looked up the method here:
http://msdn.microsoft.com/en-us/library/windows/desktop/aa393660%28v=vs.85%29.aspx
But have been unable to work out where the I am going wrong.
Thanks,
Joe
on a side note, the service I am testing, ie. making sure the service is starting, creating the text file, then stopping the service and running the "start service" code is Windows Defender. The service name is "WinDefend".
FINAL WORKING CODE:
Const ForReading = 1
strComputer = "."
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("\\vmware-host\Shared Folders\Documents\Biffduncan\Monthly Server Maintanence\service_list.txt",ForReading,True,-2)
Do Until objFile.AtEndOfStream
fLine = Split(objFile.ReadLine,",")
Set objService = objWMIService.get("Win32_Service.Name='" & fLine(0) & "'")
if InStr(fLine(2),"Running") then
'wscript.echo "it was running!"
if objService.Started then
'do nothing
else
Result = objService.StartService()
if Result <> 0 then
wscript.echo "The service: " & objService.Name & " did not start with error: " & Result
else
wscript.echo "Service " & objService.Name & " started"
end if
end if
end if
Loop
Error code 0x80041004 means that the WMI provider encountered an error after it was already initialized. The error code doesn't say anything about the cause of the error, though, nor does it provide any details. Try running WBEMTest or WMIDiag to track down the error. Also check the eventlog for related errors/warnings. If everything else fails, try rebuilding the WMI repository.
As for your code, the first thing I'd do is strip it down to the bare minimum, to avoid potential error sources:
Set wmi = GetObject("winmgmts://./root/cimv2")
Set svc = wmi.Get("Win32_Service.Name='WinDefend'")
rc = svc.StartService
WScript.Echo rc
Also, I wouldn't recommend writing the service status to a file at some random point in time, and then try starting services according to the contents of that file. There is no guarantee that the start mode hasn't been changed since the file was created, or that the service is even installed anymore.
Whether or not a service should be started is indicated by its StartMode property, so just check those services that are set to Auto. Services set to Manual will be started by the system on demand, so there's no need to launch them just because they were running when you took the snapshot.
qry = "SELECT * FROM Win32_Service WHERE StartMode='Auto'"
For Each svc In wmi.ExecQuery(qry)
If Not svc.Started Then svc.StartService
Next

Resources