Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

A server monitoring script with a twist, yes I searched 2

Status
Not open for further replies.

eraH

MIS
Dec 1, 2003
106
NZ
The below script will ping a server to see if it's up, check disk space, and check services.
I want to add a list of exclusions for the services, so that if certain services aren't running, that an alert is not generated.
Code:
'=======================================
'Configure Script
FreeSpaceSize = 0.500
'=======================================

Set objFSO = CreateObject("Scripting.FileSystemObject")

'Check that ServerList.txt exists
If Not objFSO.FileExists("ServerList.txt") Then
	WScript.Echo "File ServerList.txt Doesn't Exist. Create file ServerList.txt in same folder as script."
	WScript.Echo "Add server names to this file, each on it's own line."
	WScript.Quit
End If

'Check that ExcludedServices.txt exists
If Not objFSO.FileExists("ExcludedServices.txt") Then
	WScript.Echo "File ExcludedServices.txt Doesn't Exist. Create file ExcludedServices.txt in same folder as script."
	WScript.Echo "Add services to this file, each on it's own line."
	WScript.Quit
End If

Set objFileServers = objFSO.OpenTextFile("ServerList.txt", 1)
Set objFileExcludedServices = objFSO.OpenTextFile("ExcludedServices.txt", 1)

'Read's file one line at a time until the end of the file
Do Until objFileServers.AtEndOfStream
 strLine = objFileServers.ReadLine
	'Checks if server is up
	If Ping(strLine) = True Then
		'Checks disk space
		Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strLine & "\root\cimv2")
		Set colDisks = objWMIService.ExecQuery ("Select * from Win32_LogicalDisk Where DriveType =  3 ")
		WScript.Echo vbCrLf & "" & Ucase(strLine) & " disk space check"
		For Each objDisk in colDisks
			If FormatNumber (intFreeSpace /1024/1024/1024 ,2) < FreeSpaceSize Then
				WScript.Echo "Disk " & objDisk.DeviceID & " has " & Formatnumber(objDisk.Freespace / 1024/1024/1024 ,2) & " GB free space"
			End If
		Next
		'Checks services
		Set colRunningServices = objWMIService.ExecQuery("Select * from Win32_Service")
		WScript.Echo vbCrLf & "" & Ucase(strLine) & " services check"
		For Each objService in colRunningServices 
			If objService.State = "Stopped" And objService.StartMode = "Auto" Then
				'Wscript.Echo ExcludedServices(objService.DisplayName)
				WScript.Echo objService.DisplayName & VbTab & objService.State
			End If
		Next
	Else
		WScript.Echo "Warning - Server Down"
	End If
Loop

objFileServers.Close()
objFileExcludedServices.Close()

Function Ping(strHost)
    Dim objPing, objRetStatus
    Set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery _
      ("select * from Win32_PingStatus where address = '" & strHost & "'")

    For Each objRetStatus In objPing
        If IsNull(objRetStatus.StatusCode) Or objRetStatus.StatusCode<>0 Then
			Ping = False
        Else
            Ping = True
        End If
    Next
End Function

'Function ExcludedServices(ServiceName)
'	Do Until objFileExcludedServices.AtEndOfStream
'		strLine = objFileExcludedServices.ReadLine
'		Wscript.Echo "* File " & strLine
'		Wscript.Echo "* Service " & ServiceName
'		If strLine = ServiceName Then
'			ExcludedServices = False
'		Else
'			ExcludedServices = True
'		End If
'	Loop
'End Function
 
here is an example on how to block all Microsoft services
Code:
Select * FROM Win32_Service WHERE PathName NOT LIKE 'C: \ \ WINDOWS \ \ SYSTEM32 \ \%'

Aside from using PathName you could also use DisplayName or Name.

So to block the Alerter service you would use
Code:
Select * FROM Win32_Service WHERE Name NOT  'Alerter'

To block more than one service name
Code:
Select * FROM Win32_Service WHERE Name NOT 'Alerter' OR Name NOT 'Browser'


I hope you find this post helpful.

Regards,

Mark

Check out my scripting solutions at
Work SMARTER not HARDER. The Spider's Parlor's Admin Script Pack is a collection of Administrative scripts designed to make IT Administration easier! Save time, get more work done, get the Admin Script Pack.
 
Hi Mark,

I did a quick test of your final script with a script to list services (after juggling the syntax around a bit as my machine doesn't seem to like using NOT in this way, it only appears to work with NOT Name = 'Alerter' etc. but that's an aside [wink]).

Using the OR operator you'd still get both of the services, using the AND operator eliminates both from the list.

Regards

HarleyQuinn
---------------------------------
Carter, hand me my thinking grenades!

You can hang outside in the sun all day tossing a ball around, or you can sit at your computer and do something that matters. - Eric Cartman

Get the most out of Tek-Tips, read FAQ222-2244: How to get the best answers before posting.

 
Thanks for keeping me honest HarleyQuinn. I confess I did that from memory and did not test.
 
Thanks, got it working.
Code:
If objService.State = "Stopped" And objService.StartMode = "Auto"  And Not objService.DisplayName = "Computer Browser" Then
It's a bit unwieldy if I want to exlude a couple of services and was hoping to use a text file.
Can you see what's wrong with my code below?
Code:
'=======================================
'Configure Script
FreeSpaceSize = 0.500
'=======================================

Set objFSO = CreateObject("Scripting.FileSystemObject")

'Check that ServerList.txt exists
If Not objFSO.FileExists("ServerList.txt") Then
	WScript.Echo "File ServerList.txt Doesn't Exist. Create file ServerList.txt in same folder as script."
	WScript.Echo "Add server names to this file, each on it's own line."
	WScript.Quit
End If

'Check that ExcludedServices.txt exists
If Not objFSO.FileExists("ExcludedServices.txt") Then
	WScript.Echo "File ExcludedServices.txt Doesn't Exist. Create file ExcludedServices.txt in same folder as script."
	WScript.Echo "Add services to this file, each on it's own line."
	WScript.Quit
End If

Set objFileServers = objFSO.OpenTextFile("ServerList.txt", 1)
Set objFileExcludedServices = objFSO.OpenTextFile("ExcludedServices.txt", 1)

'Read's file one line at a time until the end of the file
Do Until objFileServers.AtEndOfStream
 strLine = objFileServers.ReadLine
	'Checks if server is up
	If Ping(strLine) = True Then
		'Checks disk space
		Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strLine & "\root\cimv2")
		Set colDisks = objWMIService.ExecQuery ("Select * from Win32_LogicalDisk Where DriveType =  3 ")
		WScript.Echo vbCrLf & "" & Ucase(strLine) & " disk space check"
		For Each objDisk in colDisks
			If FormatNumber (intFreeSpace /1024/1024/1024 ,2) < FreeSpaceSize Then
				WScript.Echo "Disk " & objDisk.DeviceID & " has " & Formatnumber(objDisk.Freespace / 1024/1024/1024 ,2) & " GB free space"
			End If
		Next
		'Checks services
		Set colRunningServices = objWMIService.ExecQuery("Select * from Win32_Service")
		WScript.Echo vbCrLf & "" & Ucase(strLine) & " services check"
		For Each objService in colRunningServices 
			'If objService.State = "Stopped" And objService.StartMode = "Auto"  And Not objService.DisplayName = "Computer Browser" Then
			If objService.State = "Stopped" And objService.StartMode = "Auto"  And ExcludedServices(objService.DisplayName) = False Then
				Wscript.Echo ExcludedServices(objService.DisplayName)
				WScript.Echo objService.DisplayName & VbTab & objService.State
			End If
		Next
	Else
		WScript.Echo "Warning - Server Down"
	End If
Loop

objFileServers.Close()
objFileExcludedServices.Close()

Function Ping(strHost)
    Dim objPing, objRetStatus
    Set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery _
      ("Select * from Win32_PingStatus Where Address = '" & strHost & "'")

    For Each objRetStatus In objPing
        If IsNull(objRetStatus.StatusCode) Or objRetStatus.StatusCode<>0 Then
			Ping = False
        Else
            Ping = True
        End If
    Next
End Function

Function ExcludedServices(ServiceName)
ExcludedServices = True
	Do Until objFileExcludedServices.AtEndOfStream
		strLine = objFileExcludedServices.ReadLine
		'Wscript.Echo "* File " & strLine
		'Wscript.Echo "* Service " & ServiceName
		If strLine = ServiceName Then
			ExcludedServices = False
		End If
	Loop
End Function
 
I think you will find it easier to read the text files all at once and make an array out of that data. Then you can loop through it and make a dictionary. The dictionary will let you check if a key exists.

A simple example:

Code:
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set WSHShell = wscript.createObject("wscript.shell")
Set objDictionary = CreateObject("scripting.dictionary")
'open the data file
Set oTextStream = oFSO.OpenTextFile("excludeList.txt")
'make an array from the data file
ExcludeArray = Split(oTextStream.ReadAll, vbNewLine)
'close the data file
oTextStream.Close
For Each strService In ExcludeArray
	objDictionary.Add strService, strService
Next

If objDictionary.Exists("Browser") Then 
	WScript.Echo "Browser service is excluded"
End If
'So you shoudl be able to do something like....
If objService.State = "Stopped" And objService.StartMode = "Auto"  And Not objDictionary.Exists(objService.DisplayName) Then

I hope you find this post helpful.

Regards,

Mark

Check out my scripting solutions at
Work SMARTER not HARDER. The Spider's Parlor's Admin Script Pack is a collection of Administrative scripts designed to make IT Administration easier! Save time, get more work done, get the Admin Script Pack.
 
Cool, I will give it a try. I was thinking of reading the files into memory once I got everything working. Looks like I will have to do it sooner.
 
Working code, there is still some code changes before I post it to the FAQ. Thanks for your help Mark, you are one smart guy.
Code:
'=======================================
'Configure Script
FreeSpaceSize = 0.500
'=======================================

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objDictionary = CreateObject("Scripting.Dictionary")

'Check that ServerList.txt exists
If Not objFSO.FileExists("ServerList.txt") Then
	WScript.Echo "File ServerList.txt Doesn't Exist. Create file ServerList.txt in same folder as script."
	WScript.Echo "Add server names to this file, each on it's own line."
	WScript.Quit
End If

'Check that ExcludedServices.txt exists
If Not objFSO.FileExists("ExcludedServices.txt") Then
	WScript.Echo "File ExcludedServices.txt Doesn't Exist. Create file ExcludedServices.txt in same folder as script."
	WScript.Echo "Add services to this file, each on it's own line."
	WScript.Quit
End If

Set objFileServers = objFSO.OpenTextFile("ServerList.txt", 1)
Set objFileExcludedServices = objFSO.OpenTextFile("ExcludedServices.txt", 1)

'Read files into arrays
ServersArray = Split (objFileServers.ReadAll, vbNewLine)
ServicesArray = Split (objFileExcludedServices.ReadAll, vbNewLine)
For Each strService In ServicesArray
    objDictionary.Add strService, strService
Next

For Each strServer in ServersArray
	'Checks if server is up
	If Ping(strServer) = True Then
		'Checks disk space
		Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strServer & "\root\cimv2")
		Set colDisks = objWMIService.ExecQuery ("Select * from Win32_LogicalDisk Where DriveType =  3 ")
		WScript.Echo vbCrLf & "" & Ucase(strServer) & " disk space check"
		For Each objDisk in colDisks
			If FormatNumber (intFreeSpace /1024/1024/1024 ,2) < FreeSpaceSize Then
				WScript.Echo "Disk " & objDisk.DeviceID & " has " & Formatnumber(objDisk.Freespace / 1024/1024/1024 ,2) & " GB free space"
			End If
		Next
		'Checks services
		Set colRunningServices = objWMIService.ExecQuery("Select * from Win32_Service")
		WScript.Echo vbCrLf & "" & Ucase(strServer) & " services check"
		For Each objService in colRunningServices 
			If objService.State = "Stopped" And objService.StartMode = "Auto"  And Not objDictionary.Exists(objService.DisplayName) Then
				WScript.Echo objService.DisplayName & VbTab & objService.State
			End If
		Next
	Else
		WScript.Echo "Warning - Server Down"
	End If
Next

objFileServers.Close()
objFileExcludedServices.Close()

Function Ping(strHost)
    Dim objPing, objRetStatus
    Set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery _
      ("Select * from Win32_PingStatus Where Address = '" & strHost & "'")

    For Each objRetStatus In objPing
        If IsNull(objRetStatus.StatusCode) Or objRetStatus.StatusCode<>0 Then
			Ping = False
        Else
            Ping = True
        End If
    Next
End Function
 
Instead of doing all those echo's why not build a report and then send that out via email using CDO so you are sure to get timely notification?

I hope you find this post helpful.

Regards,

Mark

Check out my scripting solutions at
Work SMARTER not HARDER. The Spider's Parlor's Admin Script Pack is a collection of Administrative scripts designed to make IT Administration easier! Save time, get more work done, get the Admin Script Pack.
 
I'm working on that now, I'm not very good at scripting, just persistant :) so it's takes me a while.
My plans are to let the user decide if he wants it displayed on the console or emailed.
I've also added the checks into an infinite loop.
 
Mark, this is the final script. Could you make sure it works for you before I post it to the FAQ.
Code:
'=======================================
'Configure Script
'0.500 is 500MB
FreeSpaceSize = 0.500
'10000 = 10 seconds, how often the check is run
RepeatInterval = 10000
'This can be Console or Email
AlertType = "Console"
'Email From
EmailFrom = "ServerMonitoring@to.com"
'Email To
EmailTo = "sendalert@to.com"
'Email Server
EmailServer = "myemailserver"

'=======================================

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objDictionary = CreateObject("Scripting.Dictionary")

'Check that ServerList.txt exists
If Not objFSO.FileExists("ServerList.txt") Then
	WScript.Echo "File ServerList.txt Doesn't Exist. Create file ServerList.txt in same folder as script."
	WScript.Echo "Add server names to this file, each on it's own line."
	WScript.Quit
End If

'Check that ExcludedServices.txt exists
If Not objFSO.FileExists("ExcludedServices.txt") Then
	WScript.Echo "File ExcludedServices.txt Doesn't Exist. Create file ExcludedServices.txt in same folder as script."
	WScript.Echo "Add services to this file, each on it's own line."
	WScript.Quit
End If

Set objFileServers = objFSO.OpenTextFile("ServerList.txt", 1)
Set objFileExcludedServices = objFSO.OpenTextFile("ExcludedServices.txt", 1)

'Read files into arrays
ServersArray = Split (objFileServers.ReadAll, vbNewLine)
ServicesArray = Split (objFileExcludedServices.ReadAll, vbNewLine)
For Each strService In ServicesArray
    objDictionary.Add strService, strService
Next

objFileServers.Close()
objFileExcludedServices.Close()

'Loop Forever
LoopValue = 0
Do Until LoopValue = 1
For Each strServer in ServersArray
	'Checks if server is up
	If Ping(strServer) = True Then
		'Checks disk space
		Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strServer & "\root\cimv2")
		Set colDisks = objWMIService.ExecQuery ("Select * from Win32_LogicalDisk Where DriveType =  3 ")
		For Each objDisk in colDisks
			If FormatNumber (intFreeSpace /1024/1024/1024 ,2) < FreeSpaceSize Then
				Alert("Disk")
			End If
		Next
		'Checks services
		Set colRunningServices = objWMIService.ExecQuery("Select * from Win32_Service")
		For Each objService in colRunningServices 
			If objService.State = "Stopped" And objService.StartMode = "Auto"  And Not objDictionary.Exists(objService.DisplayName) Then
				Alert("Service")
			End If
		Next
	Else
		Alert("ServerDown")
	End If
Next
WScript.Sleep (RepeatInterval)
Loop

Function Ping(strHost)
    Dim objPing, objRetStatus
    Set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery _
      ("Select * from Win32_PingStatus Where Address = '" & strHost & "'")

    For Each objRetStatus In objPing
        If IsNull(objRetStatus.StatusCode) Or objRetStatus.StatusCode<>0 Then
			Ping = False
        Else
            Ping = True
        End If
    Next
End Function

Sub Alert(strAlert)
Set objMessage = CreateObject("CDO.Message")
objMessage.From = EmailFrom
objMessage.To = EmailTo
objMessage.Configuration.Fields.Item("[URL unfurl="true"]http://schemas.microsoft.com/cdo/configuration/sendusing")[/URL] = 2
objMessage.Configuration.Fields.Item("[URL unfurl="true"]http://schemas.microsoft.com/cdo/configuration/smtpserver")[/URL] = EmailServer
objMessage.Configuration.Fields.Item("[URL unfurl="true"]http://schemas.microsoft.com/cdo/configuration/smtpserverport")[/URL] = 25 
objMessage.Configuration.Fields.Update
If AlertType = "Console" Then
	If strAlert = "Disk" Then
		WScript.Echo "Disk " & objDisk.DeviceID & " on server " & Ucase(strServer) & " has " & Formatnumber(objDisk.Freespace / 1024/1024/1024 ,2) & " GB free space"
	End If
	If strAlert = "Service" Then
		WScript.Echo objService.DisplayName & " on server " & Ucase(strServer) & " has stopped."
	End If
	If strAlert = "ServerDown" Then
		WScript.Echo Ucase(strServer) & " is down."
	End If
End If
If AlertType = "Email" Then
	If strAlert = "Disk" Then
		objMessage.Subject = "Low disk space"
		objMessage.TextBody = "Disk " & objDisk.DeviceID & " on server " & Ucase(strServer) & " has " & Formatnumber(objDisk.Freespace / 1024/1024/1024 ,2) & " GB free space"
		objMessage.Send
	End If
	If strAlert = "Service" Then
		objMessage.Subject = "Service has stopped"
		objMessage.TextBody = objService.DisplayName & " on server " & Ucase(strServer) & " has stopped."
		objMessage.Send
	End If
	If strAlert = "ServerDown" Then
		objMessage.Subject = "Service is down"
		objMessage.TextBody = Ucase(strServer) & " is down."
		objMessage.Send
	End If
	
End If
End Sub
 
Change the parts in [red]red[/red] to send the email.
Code:
report = report & "new text to add to report" & vbCrLf
report = report & "more text to add to report" & vbCrLf

SendMail(report)

Function SendMail(report)
Dim strFrom, strMyIP, strTo, strAttachmentPath
 
' Set the company specific information
strFrom = "[red]user@company.com[/red]"
' Set the SMTP server IP
strMyIP = "[red]192.168.0.13[/red]" 
' Where do you want the message to be delivered
' Use semicolons to seperate multiple addresses
strTo = "[red]me@company.com[/red]"
'strAttachmentPath = "\\server\share\file.txt"

' Set the visual basic constants as they do not exist within VBScript.
' Do not set your smtp server information here.
Const cdoSendUsingMethod = "[URL unfurl="true"]http://schemas.microsoft.com/cdo/configuration/sendusing",[/URL] _
cdoSendUsingPort = 2, _
cdoSMTPServer = "[URL unfurl="true"]http://schemas.microsoft.com/cdo/configuration/smtpserver"[/URL]

' Create the CDO connections.
Dim iMsg, iConf, Flds
Set iMsg = CreateObject("CDO.Message")
Set iConf = CreateObject("CDO.Configuration")
Set Flds = iConf.Fields

' SMTP server configuration.
With Flds
.Item(cdoSendUsingMethod) = cdoSendUsingPort

' Set the SMTP server address here.
.Item(cdoSMTPServer) = strMyIP
.Update
End With

' Set the message properties.
With iMsg
Set .Configuration = iConf
.To = strTo
.From = strFrom
.Subject = "File Update"
.TextBody = Report
' An attachment can be included.
'.AddAttachment strAttachmentPath
End With

'Send high priority
iMsg.Fields.Item("urn:schemas:mailheader:X-MSMail-Priority") = "High" ' For Outlook 2003
iMsg.Fields.Item("urn:schemas:mailheader:X-Priority") = 2 ' For Outlook 2003 also
iMsg.Fields.Item("urn:schemas:httpmail:importance") = 2 ' For Outlook Express
iMsg.Fields.Update

'Send the message.
iMsg.Send 
End Function
MsgBox "Done"

I hope you find this post helpful.  

Regards,

Mark

Check out my scripting solutions at [URL unfurl="true"]http://www.thespidersparlor.com/vbscript[/URL]

Work SMARTER not HARDER.  The Spider's Parlor's Admin Script Pack is a collection of Administrative scripts designed to make IT Administration easier!  Save time, get more work done, get the Admin Script Pack.
 
Looks like we were posting last at the same time. Your script looks OK, however I worry you will have a problem with your alerts. I would recommend that you pass both the alert type and the computer name to the alert subs to ensure that the value of the computer name has not already been changed by the loop structure.

I hope you find this post helpful.

Regards,

Mark

Check out my scripting solutions at
Work SMARTER not HARDER. The Spider's Parlor's Admin Script Pack is a collection of Administrative scripts designed to make IT Administration easier! Save time, get more work done, get the Admin Script Pack.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top