The following table lists several active script monitor context code examples that you can use to create useful active monitors for your devices. To use these examples, select the text of the context and then copy and paste the code into the Script text box of the Active Script Monitor dialog.
Note: You may have to remove the copyright information from the cut and paste if it appears when you copy from this help file.
To return the results of the script to WhatsUp Gold.
Note: This affects the state of the device.
JScript:
Context.SetResult(0, "Everything is OK"); //Success
Context.SetResult(1, "Really big big error"); //Failure
VBScript:
Context.SetResult 1, "Really big big error"
Sample Monitor 2
To log a message to the WhatsUp Gold event viewer.
Note: In order to view Context.LogMessage entries, the Debug On option in the event viewer must be selected.
JScript:
Context.LogMessage("This is the message");
Sample Monitor 3
To access the Device ID.
JScript:
var nDeviceID = Context.GetProperty("DeviceID");
Sample Monitor 4
Accessing the IP address of the device.
JScript:
var sAddress = Context.GetProperty("Address");
Sample Monitor 5
To access the device credentials.
Note: All passwords are decrypted.
JScript:
var sV1ReadCommunity = Context.GetProperty("CredSnmpV1:ReadCommunity");
var sV1WriteCommunity = Context.GetProperty("CredSnmpV1:WriteCommunity");
var sV2ReadCommunity = Context.GetProperty("CredSnmpV2:ReadCommunity");
var sV2WriteCommunity = Context.GetProperty("CredSnmpV2:WriteCommunity");
var sV3UserName = Context.GetProperty("CredSnmpV3:Username");
var sV3Context = Context.GetProperty("CredSnmpV3:Context");
var sV3AuthPassword = Context.GetProperty("CredSnmpV3:AuthPassword");
var nV3Authprotocol = Context.GetProperty("CredSnmpV3:AuthProtocol");
var sV3EncryptPassword = Context.GetProperty("CredSnmpV3:EncryptPassword");
var nV3EncryptProtocol = Context.GetProperty("CredSnmpV3:EncryptProtocol");
var sNTUsername = Context.GetProperty("CredWindows:DomainAndUserid");
var sNTPassword = Context.GetProperty("CredWindows:Password");
Sample Monitor 6
To access the WhatsUp Gold database.
This sample uses the device ID in context and accesses the 'Device' table.
JScript:
// Get the Open DB connection from the Context NameSpace
var oDb = Context.GetDB;
if (null == oDb)
{
Context.SetResult( 1, " Problem creating the PRO DB object");
}
else
{
// Get the device ID
var nDeviceID = Context.GetProperty("DeviceID");
// Retrieve all columns for this device.
var sSql = "SELECT * from Device WHERE nDeviceID = " + nDeviceID;
var oRs = oDb.Execute(sSql);
if ( !oRs.EOF )
{
// Display various columns in the debug log (Event Viewer).
var sDisplay;
sDisplay = "" + oRs("sDisplayName");
Context.LogMessage("Display Name=" + sDisplay);
sDisplay = "" + oRs("nWorstStateID");
Context.LogMessage("WorstStateID=" + sDisplay);
sDisplay = "" + oRs("sNote");
Context.LogMessage("Note=" + sDisplay);
sDisplay = "" + oRs("sStatus");
Context.LogMessage("Status=" + sDisplay);
}
Context.SetResult( 0, " Ok");
}
Sample Monitor 7
Using WMI, see who is currently logged on to a device.
You can set the monitor to be down if the logged on user is not the expected user. In this case, if no one is logged on, then the monitor is assumed up.
VBScript:
sComputer = Context.GetProperty("Address")
nDeviceID = Context.GetProperty("DeviceID")
'Assuming ICMP is not blocked and there's a ping monitor on the device, we want to
'perform the actual check only if the Ping monitor is up. ConnectServer method of
'the SWbemLocator has a long time out so it would be good to avoid unnecessary tries.
'Please note: there's no particular polling order of active monitors on a device.
'During each polling cycle, it's possible that this monitor could be polled before
'Ping is polled. If the network connection just goes down but Ping is not polled yet,
'and therefore still has an up state, this active monitor will still do an actual
'check and experience a real down. But for the subsequent polls, it won't be doing a
'real check (ConnectServer won't be called) as Ping monitor has a down state, and this
'monitor will be assumed down.
If IsPingUp(nDeviceID) = false Then
Context.SetResult 1,"Actual check was not performed due to ping being down. Automatically set to down."
Else
sAdminName = Context.GetProperty("CredWindows:DomainAndUserid")
sAdminPasswd = Context.GetProperty("CredWindows:Password")
sLoginUser = GetCurrentLoginUser(sComputer, sAdminName, sAdminPasswd)
sExpectedUser = "administrator"
If Not IsNull(sLoginUser) Then
If instr(1,sLoginUser, sExpectedUser,1) > 0 Then
Context.SetResult 0,"Current login user is " & sLoginUser
ElseIf sLoginUser = " " Then
Context.SetResult 0,"No one is currently logged in."
Else
Context.SetResult 1,"an unexpected user " & sLoginUser & " has logged in " & sComputer
End If
End If
End If
'Check if Ping monitor on the device specified by nDeviceID is up.
'If nDeviceID is not available as it's in the case during discovery, then assume
'ping is up.
'If ping monitor is not on the device, then assume it's up so the real check will be
'performed.
Function IsPingUp(nDeviceID)
If nDeviceID > -1 Then
'get the Ping monitor up state.
sSqlGetUpState = "SELECT sStateName from PivotActiveMonitorTypeToDevice as P join " & _
"ActiveMonitorType as A on P.nActiveMonitorTypeID=A.nActiveMonitorTypeID " & _
"join MonitorState as M on P.nMonitorStateID = M.nMonitorStateID " & _
"where nDeviceID=" & nDeviceID & " and A.sMonitorTypeName='Ping' and " & _
" P.bRemoved=0"
Set oDBconn = Context.GetDB
Set oStateRS = CreateObject("ADODB.Recordset")
' oStateRS.ActiveConnection = oDBconn
' oStateRS.CursorType =3 'adOpenStatic cursorType
oStateRS.Open sSqlGetUpState,oDBconn,3
'if recordset is empty then
If oStateRS.RecordCount = 1 Then
If instr(1,oStateRS("sStateName"),"up",1) > 0 Then
IsPingUp = true
Else
IsPingUP = false
End If
Else
'if there's no ping on the device, then just assume up, so regular check will happen.
IsPingUp= true
End If
oStateRS.Close
oDBconn.Close
Set oStateRS = Nothing
Set oDBconn = Nothing
Else
'assume up, since there's no device yet. It's for scanning during discovery.
IsPingUP = true
End If
End Function
'Try to get the current login user name.
Function GetCurrentLoginUser(sComputer, sAdminName, sAdminPasswd)
GetCurrentLoginUser=Null
Set oSWbemLocator = CreateObject("WbemScripting.SWbemLocator")
On Error Resume Next
Set oSWbemServices = oSWbemLocator.ConnectServer _
(sComputer, "root\cimv2",sAdminName,sAdminPasswd)
If Err.Number <> 0 Then
Context.LogMessage("The 1st try to connect to " & sComputer & " failed. Err:" & Err.Description)
Err.Clear
'If the specified user name and password for WMI connection failed, then
'try to connect without user name and password. Can't specify user name
'and password when connecting to local machine.
On Error Resume Next
Set oSWbemServices = oSWbemLocator.ConnectServer(sComputer, "root\cimv2")
If Err.Number <> 0 Then
Err.Clear
On Error Resume Next
Context.SetResult 1,"Failed to access " & sComputer & " " & _
"using username:" & sAdminName & " password." & " Err: " & Err.Description
Exit Function
End If
End If
Set colSWbemObjectSet = oSWbemServices.InstancesOf("Win32_ComputerSystem")
For Each oSWbemObject In colSWbemObjectSet
On Error Resume Next
'Context.SetResult 0,"User Name: " & oSWbemObject.UserName & " at " & sComputer
sCurrentLoginUser = oSWbemObject.UserName
Err.Clear
Next
If Cstr(sCurrentLoginUser) ="" Then
GetCurrentLoginUser = " "
Else
GetCurrentLoginUser = sCurrentLoginUser
End If
Set oSWbemServices = Nothing
Set oSWbemLocator = Nothing
End Function
Sample Monitor 8
Use SNMP to monitor the total bandwidth utilization on an interface (in + out octets) by polling values of the interface MIB.
JScript:
// Settings for this monitor:
// the interface index ifIndex:
var nInterfaceIndex = 65540;
// this monitor will fail if the interface utilization goes above this current ratio:
// current bandwidth / maxBandwidth > nMaxInterfaceUtilizationRatio
var nMaxInterfaceUtilizationRatio = 0.7; // Set to 70%
// Create an SNMP object, that will poll the device.
var oSnmpRqst = new ActiveXObject("CoreAsp.SnmpRqst");
// Get the device ID
var nDeviceID = Context.GetProperty("DeviceID");
// This function polls the device returns the ifSpeed of the inteface indexed by nIfIndex.
// ifSpeed is in bits per second.
function getIfSpeed(nIfIndex)
{
var oResult = oSnmpRqst.Initialize(nDeviceID);
if(oResult.Failed)
{
return null;
}
return parseInt(SnmpGet("1.3.6.1.2.1.2.2.1.5." + nIfIndex)); // ifSpeed
}
// Function to get SNMP ifInOctets for the interface indexed by nIfIndex (in bytes).
// Returns the value polled upon success, null in case of failure.
function getInOctets(nIfIndex)
{
var oResult = oSnmpRqst.Initialize(nDeviceID);
if(oResult.Failed)
{
return null;
}
return parseInt(SnmpGet("1.3.6.1.2.1.2.2.1.10." + nIfIndex)); // inOctets
}
// Function to get SNMP ifOutOctets for the interface indexed by nIfIndex (in bytes).
// Returns the value polled upon success, null in case of failure.
function getOutOctets(nIfIndex)
{
var oResult = oSnmpRqst.Initialize(nDeviceID);
if(oResult.Failed)
{
return null;
}
return parseInt(SnmpGet("1.3.6.1.2.1.2.2.1.16." + nIfIndex)); // outOctets
}
// Helper function to get a specific SNMP object (OID in sOid).
// Returns the value polled upon success, null in case of failure.
function SnmpGet(sOid)
{
var oResult = oSnmpRqst.Get(sOid);
if(oResult.Failed)
{
return null;
}
else
{
return oResult.GetPayload;
}
}
// Get the current date. It will be used as a reference date for the SNMP polls.
var oDate = new Date();
var nPollDate = parseInt(oDate.getTime()); // get the date in millisec in an integer.
// Do the actual polling:
var nInOctets = getInOctets(nInterfaceIndex);
var nOutOctets = getOutOctets(nInterfaceIndex);
var nIfSpeed = getIfSpeed(nInterfaceIndex);
if (nInOctets == null || nOutOctets == null || nIfSpeed == null)
{
Context.SetResult(1, "Failure to poll this device.");
}
else
{
var nTotalOctets = nInOctets + nOutOctets;
// Retrieve the octets value and date of the last poll saved in a context variable:
var nInOutOctetsMonitorPreviousPolledValue =
Context.GetProperty("nInOutOctetsMonitorPreviousPolledValue");
var nInOutOctetsMonitorPreviousPollDate =
Context.GetProperty("nInOutOctetsMonitorPreviousPollDate");
if (nInOutOctetsMonitorPreviousPolledValue == null || nInOutOctetsMonitorPreviousPollDate
== null)
{
// the context variable has never been set, this is the first time we are polling.
Context.LogMessage("This monitor requires two polls.");
Context.SetResult(0, "success");
}
else
{
// compute the bandwidth that was used between this poll and the previous poll
var nIntervalSec = (nPollDate - nInOutOctetsMonitorPreviousPollDate)/1000; // time since
last poll in seconds
var nCurrentBps = (nTotalOctets - nInOutOctetsMonitorPreviousPolledValue) * 8 /
nIntervalSec;
Context.LogMessage( "total octets for interface " + nInterfaceIndex + " = " + nTotalOctets)
;
Context.LogMessage( "previous value = " + nInOutOctetsMonitorPreviousPolledValue);
Context.LogMessage("difference: " + (nTotalOctets - nInOutOctetsMonitorPreviousPolledValue)
+ " bytes");
Context.LogMessage("Interface Speed: " + nIfSpeed + "bps");
Context.LogMessage("time elapsed since last poll: " + nIntervalSec + "s");
Context.LogMessage("Current Bandwidth utilization: "+ nCurrentBps + "bps");
if (nCurrentBps/nIfSpeed > nMaxInterfaceUtilizationRatio)
{
Context.SetResult(1, "Failure: bandwidth used on this interface " + nCurrentBps + "bps
/ total available: " + nIfSpeed + "bps is above the specified ratio: " +
nMaxInterfaceUtilizationRatio);
}
else
{
Context.SetResult(0, "Success");
}
}
// Save this poll information in the context variables:
Context.PutProperty("nInOutOctetsMonitorPreviousPolledValue", nTotalOctets)
Context.PutProperty("nInOutOctetsMonitorPreviousPollDate", nPollDate);
}
To monitor an SNMP agent running on a non standard port (161).
JScript:
var nSNMPPort = 1234; // change this value to the port your agent is running on
var oSnmpRqst = new ActiveXObject("CoreAsp.SnmpRqst");
// Get the device ID
var nDeviceID = Context.GetProperty("DeviceID");
// Initialize the SNMP request object
var oResult = oSnmpRqst.Initialize(nDeviceID);
if(oResult.Failed)
{
Context.SetResult(1, oResult.GetPayload);
}
else
{
// Set the request destination port.
var oResult = oSnmpRqst.SetPort(nSNMPPort);
// Get sysDescr.
var oResult = oSnmpRqst.Get("1.3.6.1.2.1.1.1.0");
if (oResult.Failed)
{
Context.SetResult(1, "Failed to poll device using port " + nSNMPPort + ". Error=" +
oResult.GetPayload);
}
else
{
Context.SetResult(0, "SUCCESS. Detected an SNMP agent running on port " + nSNMPPort );
}
}
Sample Monitor 10
To access SNMP using WhatsUp PRO CoreAsp.dll Interface DLL.
This code sample uses WhatsUp PRO CoreAsp.dll and uses the SnmpRqst interface.
JScript:
var oSnmpRqst = new ActiveXObject("CoreAsp.SnmpRqst");
// Get the device ID
var nDeviceID = Context.GetProperty("DeviceID");
//
// Function to get SNMP details
//
function getSnmpDetails()
{
var oResult = oSnmpRqst.Initialize(nDeviceID);
if(oResult.Failed)
{
return null;
}
var oReturnArray = new Array();
oReturnArray["sysDescr"] = SnmpGet("1.3.6.1.2.1.1.1.0"); // sysDescr
if(oReturnArray["sysDescr"] == null)
{
return null;
}
oReturnArray["objectID"] = SnmpGet("1.3.6.1.2.1.1.2.0"); // objectID
oReturnArray["sysUpTime"] = SnmpGet("1.3.6.1.2.1.1.3.0"); // sysUpTime
oReturnArray["sysContact"] = SnmpGet("1.3.6.1.2.1.1.4.0"); // sysContact
oReturnArray["sysName"] = SnmpGet("1.3.6.1.2.1.1.5.0"); // sysName
oReturnArray["sysLocation"] = SnmpGet("1.3.6.1.2.1.1.6.0"); // sysLocation
return oReturnArray;
}
//
// Helper function to get specific OID
//
function SnmpGet(sOid)
{
var oResult = oSnmpRqst.Get(sOid);
if(oResult.Failed)
{
return null;
}
else
{
return oResult.GetPayload;
}
}
//
// Get the SNMP details for the device that we passed in via the Context.
//
var oSNMPDetails = getSnmpDetails();
if(oSNMPDetails != null)
{
Context.LogMessage( "SNMP Details");
Context.LogMessage( " sysDescr=" + oSNMPDetails["sysDescr"]);
Context.LogMessage( " objectID=" + oSNMPDetails["objectID"]);
Context.LogMessage( " sysUpTime=" + oSNMPDetails["sysUpTime"]);
Context.LogMessage( " sysContact=" + oSNMPDetails["sysContact"]);
Context.LogMessage( " sysName=" + oSNMPDetails["sysName"]);
Context.LogMessage( " sysLocation=" + oSNMPDetails["sysLocation"]);
// Set success
Context.SetResult(0, "Device is SNMP enabled." );
}
else
{
// Set an error
Context.SetResult(1, "Device is not SNMP enabled.");
}