How to Monitor Windows Servers with VBScript, WMI and Monitis

Want to track a certain metric on your server which is not available out-of-the-box?  The Monitis monitoring platform provides you with the ability to monitor almost anything you can think of, including any detail on your Windows servers. Using a simple Visual Basic Script (VBS or vbscript) you will be able to read any value from WMI (Windows Management Instrumentation) and send it to Monitis’s platform for visualization, tracking and alerting — using our so-called Custom Monitoring feature.

About WMI Service

WMI is a core Windows management technology that allows software to monitor and control managed resources throughout a network. WMI gives you a consistent way to access almost any detail of the operating system (OS) such as hardware, devices, services and applications.

When it comes to authentication, in order to manage remote computers, WMI is also easy to use. WMI shares authentication mechanism with other Windows Network operations, such as accessing shared folders on networked servers. So if you can access a remote folder you can also access WMI on that computer. If you are monitoring your server in a domain — you’re probably already done.

Be sure to have Administrator privileges to be able to access all available information.

After ensuring that, if you want to monitor a remote computer just replace the dot in your computer (“.”) with the actual name of the computer to monitor in the scripts below. That’s it!

WMI service offers a wide range of objects where you can find useful information, browse available information and test your queries using WMI Explorer:  Here’s a helpful link: http://www.ks-soft.net/hostmon.eng/wmi/index.htm

Learn more about WMI here, too: http://msdn.microsoft.com/en-us/library/aa384642%28v=vs.85%29.aspx

A Monitoring Platform and API

Monitis’s platform provides an Application Programming Interface (API) to extend and automatize system management and monitoring tasks. The first thing you will need in order to access Monitis’s platform is the Monitis API Key and Secret Key.

The API Key is an alphanumeric code that allows you to access the Monitis API URLs and transmit or receive data about your Monitis services.  The Secret Key is an alphanumeric code that allows you to digitally sign your information to ensure that only you can transmit data to your Monitis account.  Your API Key may be disclosed to anyone and it is like your username, but your Secret Key must be maintained private and should not be shared or transmitted (it is like a password).  To obtain your Monitis API Key and Secret Key, log into your account and, from the top menu bar, go to Tools -> API -> API Key.

Both your API Key and your Secret Key will appear on a dialog box.

Custom Monitoring Script to Monitor Anything on Your Server

Monitis custom monitoring allows you to monitor any metric on a local or remote server, from system-level metrics to application-specific ones. Data from your custom monitor is collected and aggregated just like every other metric within Monitis’s dashboard. You may add alerting (notifications should your server go down or slow to a crawl) or customize graphical views.

In order to create your script, take the following steps:

  1. Connect to Monits API and obtain an authorization session token
  2. Create the Custom Monitor tailored to your needs.

The following VBScript code does it all for you:

apiKey = "3TE4K9JAJWCQDKRANI3IPTBLQK" 'Replace with your API key
secretKey = "5CK8P21E6A21Q9ARDDRGUJSAK" 'Replace with your secret key

 

'Connecting to WMI, "." is for local computer else specify the computer name
computer = "."
Set oWMI = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" + computer
+ "\root\cimv2")

'Finds current timezone to obtain GMT date
dtGMT = now
Set oRes = oWMI.ExecQuery("Select LocalDateTime from Win32_OperatingSystem")
For each oEntry in oRes
dtGMT = DateAdd("n", -CInt(right(oEntry.LocalDateTime, 4)), dtGMT)
next

'Initialize HTTP connection object
Set objHTTP = CreateObject("Microsoft.XMLHTTP")

'Request a token to use in following calls
url = "http://www.monitis.com/api?action=authToken&apikey=" + apiKey +
"&secretkey=" + secretKey
objHTTP.open "GET", url, False
objHTTP.send
resp = objHTTP.responseText
token = DissectStr(resp, "authToken"":""", """")

'Adds the custom monitor
url = "http://www.monitis.com/customMonitorApi"
monitorParams = "wmi_data:WMI+data:Free+space+on+C+drive:3:false;"
resultParams = "bytes:Bytes:N%2FA:2;"
name = "sample_wmi_monitor"
objHTTP.open "POST", url, False
objHTTP.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
postData = "apikey=" + apiKey + "&validation=token&authToken=" + token +
"×tamp=" + FmtDate(dtGMT) + "&action=addMonitor&monitorParams=" +
monitorParams + "&resultParams=" + resultParams + "&name=" + name +
"&tag=[wmi+sample]"
objHTTP.send postData
resp = objHTTP.responseText

Function DissectStr(cString, cStart, cEnd)
dim nStart, nEnd
nStart = InStr(cString, cStart)
if nStart = 0 then
DissectStr = ""
else
nStart = nStart + len(cStart)
if cEnd = "" then
nEnd = len(cString)
else
nEnd = InStr(nStart, cString, cEnd)
if nEnd = 0 then nEnd = nStart else nEnd = nEnd - nStart
end if
DissectStr = mid(cString, nStart, nEnd)
end if
End Function

 

Function FmtDate(dt)
FmtDate = cstr(Datepart("yyyy", dt)) + "-" + right("0"+cstr(Datepart("m", dt)),2) +
"-" + right("0"+cstr(Datepart("d", dt)),2) + " " +
right("0"+cstr(Datepart("h", dt)),2) + ":" + right("0"+cstr(Datepart("n", dt)),2) +
":" + right("0" + cstr(Datepart("S", dt)),2)
end function

Save this code to a file with a .vbs extension (such as createCustMon.vbs) and save it, then run it executing the following command from a command prompt:

cscript createCustMon.vbs

WMI Monitoring Script

Once your custom monitor is created, you can start uploading WMI query values into it.

The following steps are needed:

  1. Connect to Monits API and obtain an authToken
  2. Get the list of Custom Monitors and locate the ID of the monitor we just created
  3. Execute your WMI query on a local or remote server and get the values to upload
  4. Upload the value to the Custom Monitor using Monitis API

The following script does exactly that:
apiKey = "3TE4K9JAJWCQDKRANI3IPTBLQK" 'Replace with your API key
secretKey = "5CK8P21E6A21Q9ARDDRGUJSAK" 'Replace with your secret key

'Connecting to WMI, "." is for local computer else specify the computer name
computer = "."
Set oWMI = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" + computer
+ "\root\cimv2")

'Finds current timezone to obtain GMT date
dtGMT = now
Set oRes = oWMI.ExecQuery("Select LocalDateTime from Win32_OperatingSystem")
For each oEntry in oRes
dtGMT = DateAdd("n", -CInt(right(oEntry.LocalDateTime, 4)), dtGMT)
next

'Initialize HTTP connection object
Set objHTTP = CreateObject("Microsoft.XMLHTTP")

'Request a token to use in following calls
url = "http://www.monitis.com/api?action=authToken&apikey=" + apiKey +
"&secretkey=" + secretKey
objHTTP.open "GET", url, False
objHTTP.send
resp = objHTTP.responseText
token = DissectStr(resp, "authToken"":""", """")

'Requests the monitor list in order to find the MonitorID
tag = "[wmi+sample]"
url = "http://www.monitis.com/customMonitorApi?action=getMonitors&apikey=" + apiKey +
"&tag=" + tag
objHTTP.open "GET", url, False
objHTTP.send
resp = objHTTP.responseText
monitorID = DissectStr(resp, "id"":""", """,""tag")

'Executes the WMI Query to obtain the data
Set oRes = oWMI.ExecQuery("select FreeSpace from Win32_LogicalDisk where
DeviceID = 'C:'")
For each oEntry in oRes
value = oEntry.FreeSpace
next

'Posts data
url = "http://www.monitis.com/customMonitorApi"
action = "addResult"
results = "bytes:" & value & ";"
unixDate = CStr(DateDiff("s", "01/01/1970 00:00:00", DateSerial(Year(dtGMT),
Month(dtGMT), Day(dtGMT)) + TimeSerial(Hour(dtGMT), Minute(dtGMT), Second(dtGMT))))
+ "000"
objHTTP.open "POST", url, False
objHTTP.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
postData = "apikey=" + apiKey + "&validation=token&authToken=" + token +
"×tamp=" + FmtDate(dtGMT) + "&action=" + action + "&monitorId=" + monitorID +
"&checktime=" + unixDate + "&results=" + results
objHTTP.send postData
resp = objHTTP.responseText

Function DissectStr(cString, cStart, cEnd)
dim nStart, nEnd
nStart = InStr(cString, cStart)
if nStart = 0 then
DissectStr = ""
else
nStart = nStart + len(cStart)
if cEnd = "" then
nEnd = len(cString)
else
nEnd = InStr(nStart, cString, cEnd)
if nEnd = 0 then nEnd = nStart else nEnd = nEnd - nStart
end if
DissectStr = mid(cString, nStart, nEnd)
end if
End Function

Function FmtDate(dt)
FmtDate = cstr(Datepart("yyyy", dt)) + "-" + right("0"+cstr(Datepart("m", dt)),2) +
"-" + right("0"+cstr(Datepart("d", dt)),2) + " " +
right("0"+cstr(Datepart("h", dt)),2) + ":" + right("0"+cstr(Datepart("n", dt)),2) +
":" + right("0" + cstr(Datepart("S", dt)),2)
end function

Affix this code to a file with a .vbs extension (such as pushDataWMI.vbs) and save it. Then run it executing the following command from a command prompt:

cscript pushDataWMI.vbs

Testing the Monitor

Each time you run the second script, a value is uploaded to your Custom Monitor.
You can use Windows Task Scheduler to run the script automatically and as frequently as you need.

Add your Custom Monitor widget to your Monitis account like this:

From the Monitors menu, select and click Manage Monitors. Select Create Custom Monitor, then click Add to Window.

Refresh the page after adding new data to see them show up inside the widget.

We at Monitis hope this information on monitoring Windows WMI with VBScript will help you see how quickly and easily you can levy ur cloud-located monitoring platform to track your server and then get notified when something is wrong. That’s why we made Monitis in the first place – to save time and enhance productivity for sysadmins. Want to check your server or site? Then signup now free Monitis trial and try these scripts.

You might also like