DHCP Server - Service Discovery

DHCP_Server___Service_Discovery (WriteActionModuleType)

Script discovers DHCP related information on MOM managed computers.

Element properties:

TypeWriteActionModuleType
IsolationAny
AccessibilityInternal
RunAsDefault
InputTypeSystem.BaseData
Comment{54FA6EC8-4D61-4CF0-A13B-7FE4046F9866}

Member Modules:

ID Module Type TypeId RunAs 
RunScriptAction WriteAction System.Mom.BackwardCompatibility.ScriptResponse Default

Source Code:

<WriteActionModuleType ID="DHCP_Server___Service_Discovery" Accessibility="Internal" Comment="{54FA6EC8-4D61-4CF0-A13B-7FE4046F9866}">
<Configuration>
<IncludeSchemaTypes>
<SchemaType>MomBackwardCompatibility!System.Mom.BackwardCompatibility.AlertGenerationSchema</SchemaType>
</IncludeSchemaTypes>
<xsd:element xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="AlertGeneration" type="AlertGenerationType"/>
<xsd:element xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="InvokerType" type="xsd:integer"/>
</Configuration>
<ModuleImplementation>
<Composite>
<MemberModules>
<WriteAction ID="RunScriptAction" TypeID="MomBackwardCompatibility!System.Mom.BackwardCompatibility.ScriptResponse">
<AlertGeneration>$Config/AlertGeneration$</AlertGeneration>
<InvokerType>$Config/InvokerType$</InvokerType>
<Body><Script>
'-------------------------------------------------------------------
' &lt;company&gt;Microsoft Corporation&lt;/company&gt;
' &lt;copyright&gt;Copyright (c) Microsoft Corporation. All rights reserved.&lt;/copyright&gt;
' &lt;name&gt;
' DHCP Server - Service Discovery
' &lt;/name&gt;
' &lt;summary&gt;
' Script discovers DHCP related information on MOM managed computers.
' &lt;/summary&gt;
'-------------------------------------------------------------------
Option Explicit

Const DHCP_CLASS_ID = "DHCP"

Const DHCP_IS_AUTHORIZED_ATTRIBUTE_ID = "IsAuthorized"
Const DHCP_SERVER_NAME_ATTRIBUTE_ID = "ServerName"

Const DHCP_AUTHORIZED_COMPONENT_ID = "Authorized"
Const DHCP_PERFORMANCE_COMPONENT_ID = "Performance"
Const DHCP_SERVICES_COMPONENT_ID = "Service"


Const COMPUTER_CLASS_ID = "Computer"

Const COMPUTER_COMPUTER_NAME_ATTRIBUTE_ID = "ComputerName"
Const COMPUTER_TIME_ZONE_BIAS_ATTRIBUTE_ID = "Time Zone Bias"
Const COMPUTER_OPERATING_SYSTEM_VERSION_ATTRIBUTE_ID = "Operating System Version"
Const COMPUTER_IP_ADDRESS_ATTRIBUTE_ID = "IPAddress"
Const COMPUTER_FQDN_ATTRIBUTE_ID = "FQDN"
Const COMPUTER_VIRTUAL_SERVER_TYPE_ATTRIBUTE_ID = "Virtual Server Type"

Const ALERT_SUCCESS = 10
Const ALERT_INFORMATION = 20
Const ALERT_WARNING = 30
Const ALERT_ERROR = 40
Const ALERT_CRITICAL_ERROR = 50
Const ALERT_SECURITY_BREACH = 60
Const ALERT_SERVICE_UNAVAILABLE = 70

Const PROBLEMSTATE_NOTSET = 0
Const PROBLEMSTATE_GREEN = 1
Const PROBLEMSTATE_GREY = 2
Const PROBLEMSTATE_RED = 3

''******************************************************************************
' Name: CreateAlert
'
' Purpose: Creates, but does not submit, an alert
'
' Parameters:
' iSeverity - The severity of the alert.
' sName - The name of the alert.
' sDescription - The alert description.
' sRole - The server role
' sInstance - The server role instance for which to issue a state alert.
' sComponent - The component affected
' iProblemState - The problem state
'
Function CreateAlert(ByVal iSeverity, ByVal sName, ByVal sDescription, ByVal sRole, ByVal sInstance, ByVal sComponent, ByVal iProblemState)
Dim oAlert

Set oAlert = ScriptContext.CreateAlert()

oAlert.Name = sName
oAlert.Description = sDescription
oAlert.AlertSource = "DHCP Server - Service Discovery"
oAlert.AlertLevel = iSeverity

'If there is a role, instance and component specified then this is a state alert
If sRole &lt;&gt; "" And sInstance &lt;&gt; "" And sComponent &lt;&gt; "" Then
oAlert.ProblemState = iProblemState
oAlert.ServerRole = sRole
oAlert.ServerRoleInstance = sInstance
oAlert.Component = sComponent
oAlert.ComponentInstance = ""
End If

Set CreateAlert = oAlert
End Function

''******************************************************************************
' Name: Submit Alert
'
' Purpose: Raises an alert
'
' Parameters:
' iSeverity - The severity of the alert.
' sName - The name of the alert.
' sDescription - The alert description.
' sRole - The server role
' sInstance - The server role instance for which to issue a state alert.
' sComponent - The component affected
' iProblemState - The problem state
'
Sub SubmitAlert(ByVal iSeverity, ByVal sName, ByVal sDescription, ByVal sRole, ByVal sInstance, ByVal sComponent, ByVal iProblemState)
ScriptContext.Submit CreateAlert(iSeverity, sName, sDescription, sRole, sInstance, sComponent, iProblemState)
End Sub

Function IsValidObject(ByVal oObject)
IsValidObject = False

If IsObject(oObject) Then
If Not oObject Is Nothing Then
IsValidObject = True
End If
End If
End Function

Const EVENT_TYPE_SUCCESS = 0
Const EVENT_TYPE_ERROR = 1
Const EVENT_TYPE_WARNING = 2
Const EVENT_TYPE_INFORMATION = 4
Const EVENT_TYPE_AUDITSUCCESS = 8
Const EVENT_TYPE_AUDITFAILURE = 16

Function ThrowScriptErrorNoAbort(ByVal sMessage, ByVal oErr)
'
' ThrowScriptError :: Creates an event and sends it back to the mom server
'
'

Dim sErrDescription, sErrNumber
sErrDescription = oErr.Description
sErrNumber = oErr.Number

On Error Resume Next

Dim oScriptErrorEvent

Set oScriptErrorEvent = ScriptContext.CreateEvent()
With oScriptErrorEvent
.EventNumber = 40000
.EventType = EVENT_TYPE_ERROR
.Message = sMessage
.SetEventParameter """Microsoft Windows DHCP Server"""
.SetEventParameter sMessage
.SetEventParameter sErrDescription
.SetEventParameter sErrNumber
End With
ScriptContext.Submit oScriptErrorEvent
ScriptContext.Echo "ThrowScriptError('" &amp; sMessage &amp; "')"
End Function

Function ThrowScriptError(Byval sMessage, ByVal oErr)
'
' ThrowScriptError :: Creates an event and sends it back to the mom server
'
'
On Error Resume Next
ThrowScriptErrorNoAbort sMessage, oErr
ScriptContext.Quit()
End Function

Class Error
Private m_lNumber
Private m_sSource
Private m_sDescription
Private m_sHelpContext
Private m_sHelpFile
Public Sub Save()
m_lNumber = Err.number
m_sSource = Err.Source
m_sDescription = Err.Description
m_sHelpContext = Err.HelpContext
m_sHelpFile = Err.helpfile
End Sub
Public Sub Raise()
Err.Raise m_lNumber, m_sSource, m_sDescription, m_sHelpFile, m_sHelpContext
End Sub
Public Sub Clear()
m_lNumber = 0
m_sSource = ""
m_sDescription = ""
m_sHelpContext = ""
m_sHelpFile = ""
End Sub
Public Default Property Get Number()
Number = m_lNumber
End Property
Public Property Get Source()
Source = m_sSource
End Property
Public Property Get Description()
Description = m_sDescription
End Property
Public Property Get HelpContext()
HelpContext = m_sHelpContext
End Property
Public Property Get HelpFile()
HelpFile = m_sHelpFile
End Property
End Class

Function MomGetObject(ByVal sMoniker)
Set MomGetObject = Nothing

Dim oError
Set oError = New Error

On Error Resume Next
Set MomGetObject = GetObject(sMoniker)
oError.Save
On Error Goto 0

If oError.Number &lt;&gt; 0 Then ThrowScriptErrorNoAbort "Unable to get the object '" &amp; sMoniker &amp; "'", oError
End Function

'Define global vars
Dim g_oUtil

'=============
' Method: Main
' Description: The Sub called by MOM Runtime (with ScriptContext object)
'=============
Sub Main()
'log information
Set g_oUtil = new Util

Call g_oUtil.SetDebugLevel(g_oUtil.DBG_ERROR)
Call g_oUtil.LogMessage(g_oUtil.DBG_TRACE, "DHCP Service Discovery starting: at machine local time: " + CStr(Time))

DoDHCPDiscovery

Call g_oUtil.LogMessage(g_oUtil.DBG_TRACE, "Done with Service Discovery Script at local time: " + CStr(time))
End Sub

'=============
' Method: DoDHCPDiscovery
' Description: Perform DHCP service discovery.
'=============
Sub DoDHCPDiscovery()
Dim objDiscData
Dim oDHCPCollection
Dim oDHCPInstance
Dim strIsAuthorized
Dim bIsAuthorized

'log trace
Call g_oUtil.LogMessage(g_oUtil.DBG_TRACE, "Starting DHCP Computer Discovery.")

'Create Discovery Data MOM Event
Call g_oUtil.LogMessage(g_oUtil.DBG_TRACE, "Creating DiscoveryData packet." )
Set objDiscData = ScriptContext.CreateDiscoveryData
objDiscData.ScopeID = "{e65efad3-cd83-4504-8a34-802dfb38b747}"


'get Authorization status from AD
bIsAuthorized = IsAuthorized()

Select Case bIsAuthorized
Case True
strIsAuthorized = "Yes"
Case False
strIsAuthorized = "No"
Case Else
strIsAuthorized = ""
End Select

'creating this OS Computer Instance
Call g_oUtil.LogMessage(g_oUtil.DBG_TRACE, "Creating DHCP Computer instance ( " + _
" Server= " + ScriptContext.TargetNetbiosComputer + _
")")

Set oDHCPCollection = objDiscData.CreateCollection
With oDHCPCollection
.ClassID = DHCP_CLASS_ID
.AddScopeFilter COMPUTER_COMPUTER_NAME_ATTRIBUTE_ID, ScriptContext.TargetComputerIdentity
.AddScopeProperty DHCP_IS_AUTHORIZED_ATTRIBUTE_ID
If strIsAuthorized = "" Then .AddScopeComponent DHCP_AUTHORIZED_COMPONENT_ID
End With

Set oDHCPInstance = oDHCPCollection.CreateInstance
With oDHCPInstance
.AddKeyProperty DHCP_SERVER_NAME_ATTRIBUTE_ID, ScriptContext.TargetNetbiosComputer
.AddProperty DHCP_IS_AUTHORIZED_ATTRIBUTE_ID, strIsAuthorized
End With

oDHCPCollection.AddInstance oDHCPInstance
objDiscData.AddCollection oDHCPCollection

'submit the discovery data packet
Call g_oUtil.LogMessage(g_oUtil.DBG_TRACE, "Submitting Discovery data packet.")
ScriptContext.Submit objDiscData

' Commenting out as we no longer use the script to check out auth status. Instead we use ntevents and a event rule to set state.
'SetAuthorizationState bIsAuthorized
End Sub

Sub SetAuthorizationState(ByVal bIsAuthorized)
If IsNull(bIsAuthorized) Then Exit Sub

Dim iAlertLevel
Dim sAlertDescription
Dim iProblemState

Select Case bIsAuthorized
Case True
iAlertLevel = ALERT_SUCCESS
sAlertDescription = "DHCP is authorized"
iProblemState = PROBLEMSTATE_GREEN
Case False
iAlertLevel = ALERT_CRITICAL_ERROR
sAlertDescription = "DHCP is not authorized"
iProblemState = PROBLEMSTATE_RED
End Select

SubmitAlert iAlertLevel, _
"DHCP Authorization", _
sAlertDescription, _
DHCP_CLASS_ID, _
ScriptContext.TargetNetbiosComputer, _
DHCP_AUTHORIZED_COMPONENT_ID, _
iProblemState
End Sub

'Returns true if authorized, false if not, and null on error
Function IsAuthorized()
IsAuthorized = Null

Dim oRootDSE
On Error Resume Next
Set oRootDSE = GetObject("LDAP://rootdse")
On Error Goto 0
If Not IsValidObject(oRootDSE) Then Exit Function

Dim sConfigNC
sConfigNC = oRootDSE.Get("configurationNamingContext")

Dim oNetServicesContainer
Set oNetServicesContainer = MomGetObject("LDAP://CN=NetServices,CN=Services," &amp; sConfigNC)
If Not IsValidObject(oNetServicesContainer) Then Exit Function

Dim aDHCPServers
Dim sDHCPServer

oNetServicesContainer.Filter = Array("dHCPClass")

Dim oAuthorizedServer
For Each oAuthorizedServer In oNetServicesContainer
aDHCPServers = Empty
On Error Resume Next
aDHCPServers = oAuthorizedServer.GetEx("dhcpServers")
On Error Goto 0
If Not IsEmpty(aDHCPServers) Then
For Each sDHCPServer In aDHCPServers
If DHCPServerDNSNameMatch(sDHCPServer, ScriptContext.TargetComputer) Then
IsAuthorized = True
Exit Function
End If
Next
End If
Next

IsAuthorized = False
End Function

Function DHCPServerDNSNameMatch(ByVal sDHCPServer, ByVal sDNSName)
DHCPServerDNSNameMatch = (InStr(1, sDHCPServer, "$s" &amp; sDNSName &amp; "$", vbTextCompare) &lt;&gt; 0)
End Function



'==========================================================================
' Class: Util
' Description: Utility methods for logging, creating MOM alert
'==========================================================================
Class Util

' Used to say to LogMessage when/how to print the message.
Public DBG_NONE
Public DBG_ERROR
Public DBG_WARNING
Public DBG_TRACE

'Internal Debug Level
Private m_nDebugLevel
'---------------
' Methods
'---------------

'=============
' Method: Class_Initialize
' Description: This is the constructor
' Parameters:
'=============
Private Sub Class_Initialize()
' Initialize Debug level constants
DBG_TRACE = 1
DBG_WARNING = 2
DBG_ERROR = 3
DBG_NONE = 4

'by default only errors are logged
m_nDebugLevel = DBG_ERROR

End Sub

'=============
' Method: Class_Terminate
' Description: This is the destructor
' Parameters:
'=============
Private Sub Class_Terminate()
End Sub

'=============
' Method: SetDebugLevel
' Description: To change the debugging output level of information
' generated by this utility.
' Parameters:
' nLevel - Level, either DBG_NONE, DBG_TRACE,
' DBG_WARNING or DBG_ERROR
'=============
Public Sub SetDebugLevel(ByVal nLevel)
m_nDebugLevel = nLevel
End Sub

'=============
' Method: LogMessage
' Description: Log a debug message to ScriptContext
' Parameters:
' nLevel - Debug level for the message that we're logging.
' strMessage - The message to write to the trace.
'=============
Public Sub LogMessage( _
ByVal nLevel, _
ByVal strMessage _
)
If (nLevel &gt;= m_nDebugLevel) Then
if (nLevel = DBG_ERROR) Then
ScriptContext.Echo "[Error]: " + strMessage
ElseIf (nLevel = DBG_WARNING) Then
ScriptContext.Echo "[Warning]: " + strMessage
ElseIf (nLevel = DBG_TRACE) Then
ScriptContext.Echo "[Trace]:" + strMessage
End If
End If
End Sub

End Class</Script></Body>
<Language>VBScript</Language>
<Name>DHCP Server - Service Discovery</Name>
<Parameters/>
<ManagementPackId>[Microsoft.Windows.Server.DHCP,,1.0.0.1]</ManagementPackId>
</WriteAction>
</MemberModules>
<Composition>
<Node ID="RunScriptAction"/>
</Composition>
</Composite>
</ModuleImplementation>
<InputType>SystemLibrary!System.BaseData</InputType>
</WriteActionModuleType>