Monday, February 16, 2009

Script Code: Active Directory Data Extraction

Here's a portion of a script that I used to extract information from client Active Directory environments to assess their "health" and for supporting project plans, etc. I don't use it anymore, so maybe it can benefit someone else.  If this doesn't suit your needs, feel free to modify it.  You can find tons of other scripts to do this as well if you search the web.  Check out Don Hite's web site, as well as Cruto for other examples.

'****************************************************************
' Filename..: ad_env_query.vbs
' Author....: David Stein
' Date......: 11/21/07
' Purpose...: query active directory forest envirnment information
' SQL.......: N/A
' Comments..: usage:
'
'   cscript /nologo ad_env_query.vbs
'
'   to capture output to file, append output redirect...
'
'   cscript /nologo ad_env_query.vbs >ad_query.txt
'****************************************************************

'----------------------------------------------------------------
' comment: toggle options on/off via the following variables
'----------------------------------------------------------------

' these control showing total counts for objects

Const CountUsers       = False ' count user accounts
Const CountGroups      = False ' count security groups
Const CountComputers   = False ' count computers
Const CountPrinters    = False ' count published shared printers
Const CountServers     = False ' count servers
Const CountSpecUsers   = False ' count users with non-exp passwords
Const CountContacts    = False ' count contacts
Const CountDisabled    = False ' count disabled user accounts

' these control enumerating object names

Const ShowAllDomains   = False ' show all domains in forest
Const ShowAllUsers     = False ' show user accounts
Const ShowSpecUsers    = False ' show users with non-exp passwords
Const ShowAllContacts  = False ' show contacts
Const ShowAllGroups    = False ' show security groups
Const ShowAllComputers = False ' show computers
Const ShowAllPrinters  = False ' show published shared printers
Const ShowAllTrusts    = False ' show domain trusts
Const ShowAllShares    = False ' show published shares
Const ShowAllDisabled  = False ' show disabled user accounts

' these control enumerating domain structural items

Const ShowFSMO       = False ' show fsmo role holders
Const ShowAllSites   = False ' show all ad sites
Const ShowRootInfo   = False ' show RootDSE properties
Const ShowOUs        = False ' show OU tree structure
Const ShowContainers = True ' include containers when showing OU structure
Const ShowAllGPOs    = False ' show all group policy objects
Const ShowNetlogon   = False ' show contents of netlogon share

' note: [ShowContainers] is only used when [ShowOUs] is TRUE

'----------------------------------------------------------------
' ***  IMPORTANT: DO NOT MODIFY CODE BELOW THIS POINT !!!  ***
'----------------------------------------------------------------
Dim LDAP_DN, objRootDSE, objWMIService, wshNetwork, wshShell
Dim ADSI_DN, objFSO

Const NTDSDSA_OPT_IS_GC = 1
Const ADS_SCOPE_SUBTREE = 2
Const ADS_UF_ACCOUNTDISABLE = 2
Const strComputer = "."

On Error Resume Next
Set objRootDSE = GetObject("LDAP://rootDSE")
Set wshNetwork = CreateObject("WScript.Network")
Set wshShell   = CreateObject("WScript.Shell")
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
Set objFSO = CreateObject("Scripting.FileSystemObject")
If err.Number <> 0 Then
    wscript.echo "ERROR: Failed to instantiate objects required for query"
    wscript.echo "Details: " & err.Number & " / " & err.Description
    wscript.Quit
End If

'----------------------------------------------------------------
' comment: query for LDAP domain DN (eg. DC=domain,DC=com)
'----------------------------------------------------------------

LDAP_DN = Domain_LDAP()
ADSI_DN = Domain_NetBIOS(LDAP_DN)

'----------------------------------------------------------------
' comment: begin processing
'----------------------------------------------------------------

ShowBasicInfo()
ShowPwdPolicy()
ShowDomainControllers()

If ShowRootInfo = True Then ShowRootDSEinfo()
If ShowAllDomains = True Then ShowDomains()
If ShowAllTrusts = True Then ShowTrusts()
If ShowFSMO = True Then ShowRoles()
If ShowAllSites = True Then ShowSites()
If ShowOUs = True Then EnumOUs()

If CountComputers = True Then EnumComputers "COUNT"
If CountServers = True Then EnumServers "COUNT"
If CountGroups = True Then EnumGroups "COUNT"
If CountUsers = True Then EnumUsers "COUNT"
If CountSpecUsers = True Then ShowSpecialUsers "COUNT"
If CountDisabled = True Then EnumDisabledUsers "COUNT"
If CountContacts = True Then EnumContacts "COUNT"
If CountPrinters = True Then EnumPrinters "COUNT"

If ShowAllServers = True Then EnumServers ""
If ShowAllComputers = True Then EnumComputers ""
If ShowAllGroups = True Then EnumGroups ""
If ShowAllUsers = True Then EnumUsers ""
If ShowSpecUsers = True Then ShowSpecialUsers ""
If ShowAllDisabled = True Then EnumDisabledUsers ""
If ShowAllContacts = True Then EnumContacts ""
If ShowAllPrinters = True Then EnumPrinters ""
If ShowAllGPOs = True Then EnumGPOs()
If ShowNetlogon = True Then NetlogonShare()
If ShowAllShares = True Then EnumShares ""

'ShowOU_GPO_Info "LDAP://ou=Domain Controllers," & LDAP_DN

Set wshNetwork = Nothing
Set wshShell   = Nothing

'----------------------------------------------------------------

Function Domain_LDAP()
    Dim retval
    retval = objRootDSE.Get("defaultNamingContext")
    Domain_LDAP = retval
End Function

'----------------------------------------------------------------

Function Domain_NetBIOS(ldapdn)
    Domain_NetBIOS = Replace(Replace(ldapdn,"DC=",""),",",".")
End Function

'----------------------------------------------------------------

Sub ShowBasicInfo()
    wscript.echo vbCRLF & "# GENERAL INFORMATION" & vbCRLF
    Dim strPCName, strUserName, strDomain
    strPCName   = wshNetwork.ComputerName
    strUserName = wshNetwork.UserName
    strDomain   = wshNetwork.UserDomain
    wscript.echo "user_domain....: " & strDomain
    wscript.echo "domain_ldap....: " & LDAP_DN
    wscript.echo "computername...: " & strPCName
    wscript.echo "username.......: " & strUserName
    wscript.echo "report_date....: " & Now
End Sub

'----------------------------------------------------------------

Sub ShowPwdPolicy()
    Dim objDomain, maxPwdAge, minPwdAge, minPwdLen
    Dim acctLockoutDur, acctLockoutThreshold, acctLockoutWait
    Dim pwdHistory
    Set objDomain = GetObject("LDAP://" & objRootDSE.Get("defaultNamingContext"))

    'convert to days...
    maxPwdAge = Int(Int8ToSec(objDomain.Get("maxPwdAge")) / 86400)

    'convert to days...
    minPwdAge = Int8ToSec(objDomain.Get("minPwdAge")) / 86400

    minPwdLen = objDomain.Get("minPwdLength")

    'convert to minutes...
    acctLockoutDur = Int8ToSec(objDomain.Get("lockoutDuration")) / 60
    acctLockoutThreshold = objDomain.Get("lockoutThreshold")

    'convert to minutes...
    acctLockoutWait = Int8ToSec(objDomain.Get("lockoutObservationWindow")) / 60 
    pwdHistory = objDomain.Get("pwdHistoryLength")
    wscript.echo vbCRLF & "# DOMAIN PASSWORD POLICY SETTINGS" & vbCRLF
    wscript.echo "max_pwd_age....: " & maxPwdAge & " days"
    wscript.echo "min_pwd_age....: " & minPwdAge & " days"
    wscript.echo "pwd_history....: " & pwdHistory & " passwords remembered"
    wscript.echo "min_pwd_length.: " & minPwdLen & " chars"
    wscript.echo "lockout_dur....: " & acctLockoutDur & " minutes"
    wscript.echo "lockout_thresh.: " & acctLockoutThreshold & " invalid logon attempts"
    wscript.echo "reset_wait.....: " & acctLockoutWait & " minutes"
End Sub

'----------------------------------------------------------------
' function: convert Integer8 64-bit numbers to seconds (time)
'----------------------------------------------------------------

Function Int8ToSec(ByVal objInt8)
    Dim lngHigh, lngLow
    lngHigh = objInt8.HighPart
    ' adjust for error in IADsLargeInteger property methods
    lngLow = objInt8.LowPart
    If lngLow < 0 Then
        lngHigh = lngHigh + 1
    End If
    Int8ToSec = -(lngHigh * (2 ^ 32) + lngLow) / (10000000)
End Function

'----------------------------------------------------------------

Sub ShowDomains()
    Dim objWMIAD, colItems, objItem
    wscript.echo vbCRLF & "# ACTIVE DIRECTORY DOMAINS" & vbCRLF
    On Error Resume Next
    Set objWMIAD = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _
        strComputer & "\root\MicrosoftActiveDirectory")
    Set colItems = objWMIAD.ExecQuery("Select * from Win32_NTDomain")
    For Each objItem in colItems
        If Trim(objItem.DomainName) <> "" Then
            wscript.echo "domain_name....: " & objItem.DomainName
            wscript.echo "client_sitename: " & objItem.ClientSiteName
            wscript.echo "dc_sitename....: " & objItem.DcSiteName
            wscript.echo "description....: " & objItem.Description
            wscript.echo "dns_forestname.: " & objItem.DnsForestName
            wscript.echo "dc_address.....: " & objItem.DomainControllerAddress
            wscript.echo "dc_address_type: " & objItem.DomainControllerAddressType
            wscript.echo "dc_name........: " & objItem.DomainControllerName
            wscript.echo "domain_guid....: " & objItem.DomainGuid
            wscript.echo "ds_flag........: " & objItem.DSDirectoryServiceFlag
            wscript.echo "ds_dns_contflag: " & objItem.DSDnsControllerFlag
            wscript.echo "ds_dns_domflag.: " & objItem.DSDnsDomainFlag
            wscript.echo "ds_dns_forflag.: " & objItem.DSDnsForestFlag
            wscript.echo "ds_gc_flag.....: " & objItem.DSGlobalCatalogFlag
            wscript.echo "ds_kdc_flag....: " & objItem.DSKerberosDistributionCenterFlag
            wscript.echo "ds_pdc_flag....: " & objItem.DSPrimaryDomainControllerFlag
            wscript.echo "ds_timesvc_flag: " & objItem.DSTimeServiceFlag
            wscript.echo "ds_write_flag..: " & objItem.DSWritableFlag
    '        wscript.echo "name...........: " & objItem.Name
    '        wscript.echo "primary_owner..: " & objItem.PrimaryOwnerContact
            wscript.echo
        End If
    Next
End Sub

'----------------------------------------------------------------

Sub ShowDomainControllers()
    Dim objConnection, objCommand, objRecordSet, objDC, icount
    wscript.echo vbCRLF & "# DOMAIN CONTROLLERS" & vbCRLF
    Set objConnection = CreateObject("ADODB.Connection")
    Set objCommand = CreateObject("ADODB.Command")
    objConnection.Provider = "ADsDSOObject;"
    objConnection.open
    objCommand.ActiveConnection = objConnection
    icount = 0
    ldapQuery = "<LDAP://" & objRootDSE.Get("ConfigurationNamingContext") & _
        ">;((objectClass=nTDSDSA));ADsPath;subtree"
    objCommand.CommandText = ldapQuery
    objCommand.Properties("Page Size") = 1000
    Set objRecordSet = objCommand.Execute
    If Not(objRecordSet.EOF And objRecordSet.BOF) Then
        Do While Not(objRecordSet.EOF)
            Set objDC = GetObject(GetObject(objRecordSet.Fields(0).Value).Parent)
            wscript.echo "dc_server_name.: " & objDC.dNSHostName
            objRecordSet.MoveNext
            icount = icount + 1
        Loop
        wscript.echo "dc_servers.....: " & icount
    End If
    objConnection.Close
End Sub

'----------------------------------------------------------------

Sub ShowRoles()
    Dim objSchema, objNtds, objPartitions, objDomain, objRidManager
    Dim objInfrastructure, strSchemaMaster, objComputer, strDomainNamingMaster
    Dim strPdcEmulator, strRidMaster, strInfrastructureMaster
    wscript.echo vbCRLF & "# ACTIVE DIRECTORY SERVER ROLES" & vbCRLF
    Set objSchema = GetObject("LDAP://" & objRootDSE.Get("schemaNamingContext"))
    strSchemaMaster = objSchema.Get("fSMORoleOwner")
    Set objNtds = GetObject("LDAP://" & strSchemaMaster)
    Set objComputer = GetObject(objNtds.Parent)
    wscript.echo "fsmo_schema....: " & objComputer.Name
    Set objNtds = Nothing
    Set objComputer = Nothing
 

    Set objPartitions = GetObject("LDAP://CN=Partitions," & _

        objRootDSE.Get("configurationNamingContext"))


    strDomainNamingMaster = objPartitions.Get("fSMORoleOwner")
    Set objNtds = GetObject("LDAP://" & strDomainNamingMaster)
    Set objComputer = GetObject(objNtds.Parent)
    wscript.echo "fsmo_domain....: " & objComputer.Name

    Set objDomain = GetObject("LDAP://" & objRootDSE.Get("defaultNamingContext"))
    strPdcEmulator = objDomain.Get("fSMORoleOwner")
    Set objNtds = GetObject("LDAP://" & strPdcEmulator)
    Set objComputer = GetObject(objNtds.Parent)
    wscript.echo "fsmo_pdc.......: " & objComputer.Name

    Set objRidManager = GetObject("LDAP://CN=RID Manager$,CN=System," & _

        objRootDSE.Get("defaultNamingContext"))


    strRidMaster = objRidManager.Get("fSMORoleOwner")
    Set objNtds = GetObject("LDAP://" & strRidMaster)
    Set objComputer = GetObject(objNtds.Parent)
    wscript.echo "fsmo_rid.......: " & objComputer.Name

    Set objInfrastructure = GetObject("LDAP://CN=Infrastructure," & _

        objRootDSE.Get("defaultNamingContext"))


    strInfrastructureMaster = objInfrastructure.Get("fSMORoleOwner")
    Set objNtds = GetObject("LDAP://" & strInfrastructureMaster)
    Set objComputer = GetObject(objNtds.Parent)
    wscript.echo "fsmo_im........: " & objComputer.Name
End Sub

'----------------------------------------------------------------

Sub ShowSites()
    Dim strConfigurationNC, strSitesContainer, objSite, sitename
    wscript.echo vbCRLF & "# ACTIVE DIRECTORY SITES" & vbCRLF
    strConfigurationNC = objRootDSE.Get("configurationNamingContext")
    strSitesContainer = "LDAP://cn=Sites," & strConfigurationNC
    Set objSitesContainer = GetObject(strSitesContainer)
    objSitesContainer.Filter = Array("site")
    For Each objSite In objSitesContainer
        sitename = Replace(objSite.Name,"CN=","")
        wscript.echo "site_name......: " & sitename
        ShowSiteDCs objSite.Name
        ShowSiteSubnets objSite.Name
    Next
End Sub

'----------------------------------------------------------------

Sub ShowSiteDCs(strSiteRDN)
    Dim strConfigurationNC, strServersPath, objServer, sitename
    strConfigurationNC = objRootDSE.Get("configurationNamingContext")
    strServersPath = "LDAP://cn=Servers," & strSiteRDN & ",cn=Sites," & strConfigurationNC
    Set objServersContainer = GetObject(strServersPath)
    For Each objServer In objServersContainer
        servername = Replace(objServer.Name,"CN=","")
        sitename = Replace(strSiteRDN,"CN=","")
        wscript.echo vbTab & "dc_server....: " & servername
        ShowConnections servername, sitename
        ShowBridgeHeadTransports servername, sitename
    Next
End Sub

'----------------------------------------------------------------

Sub ShowSiteSubnets(strSiteRDN)
    Dim strConfigurationNC, strSitePath, arrSiteObjectBL 
    Dim strSiteObjectBL
    strConfigurationNC = objRootDSE.Get("configurationNamingContext")
    strSitePath = "LDAP://" & strSiteRDN & ",cn=Sites," & strConfigurationNC
    Set objSite = GetObject(strSitePath)
    objSite.GetInfoEx Array("siteObjectBL"), 0
    arrSiteObjectBL = objSite.GetEx("siteObjectBL")
    For Each strSiteObjectBL In arrSiteObjectBL
        wscript.echo vbTab & "subnet.......: " & _

            Split(Split(strSiteObjectBL, ",")(0), "=")(1)
    Next
End Sub

'----------------------------------------------------------------

Sub EnumOUs()
    wscript.echo vbCRLF & "# ORGANIZATIONAL UNIT STRUCTURE" & vbCRLF
    DisplayObjects "LDAP://" & LDAP_DN, ""
End Sub

Function DisplayObjects( strADsPath, strTab)
    Set objObject = GetObject(strADsPath)
    Set objX = GetObject(strADsPath)
'    wscript.echo strTab & Replace(objX.Name, "OU=", "")
    wscript.echo strTab & objX.Name
    If showContainers = True Then
        objObject.Filter = Array("container","organizationalUnit")
    Else
        objObject.Filter = Array("organizationalUnit")
    End If
    For each objChildObject in objObject
        DisplayObjects objChildObject.ADsPath, strTab & " .. "
    Next
End Function

'----------------------------------------------------------------

Function IsGC(strCN)
    Dim strDsServiceDN, intOptions, objServer
    Set objServer = GetObject("LDAP://" & strCN & "/rootDSE")
    strDsServiceDN = objServer.Get("dsServiceName")
    Set objDsRoot  = GetObject("LDAP://" & strCN & "/" & strDsServiceDN)
    intOptions = objDsRoot.Get("options")
    If intOptions And NTDSDSA_OPT_IS_GC Then
        IsGC = True
    End If
End Function

'----------------------------------------------------------------

Sub ShowTrusts()
    Dim colTrustList, objTrust
    wscript.echo vbCRLF & "ACTIVE DIRECTORY TRUSTS" & vbCRLF
    On Error Resume Next
    If err.Number <> 0 Then
        wscript.echo "unavailable....: non-domain-controller"
        Exit Sub
    End If
    Set colTrustList = objWMIService.ExecQuery("Select * from Microsoft_DomainTrustStatus")
    For each objTrust in colTrustList
        wscript.echo "trusted_domain.: " & objTrust.TrustedDomain
        wscript.echo "trust_direction: " & objTrust.TrustDirection
        wscript.echo "trust_type.....: " & objTrust.TrustType
        wscript.echo "trust_attribs..: " & objTrust.TrustAttributes
        wscript.echo "trusted_dcname.: " & objTrust.TrustedDCName
        wscript.echo "trust_status...: " & objTrust.TrustStatus
        wscript.echo "trust_is_ok....: " & objTrust.TrustIsOK
    Next
End Sub

'----------------------------------------------------------------

Sub EnumServers(mode)
    wscript.echo vbCRLF & "# enumerating server objects..." & vbCRLF
    Dim objRecordSet, varConfigNC, strConnString, strWQL
    Dim objServer, strServerName, strOperatingSystem, retval
    retval = 0
    Set objRecordSet = CreateObject("ADODB.RecordSet")
    varConfigNC = objRootDSE.Get("defaultNamingContext")
    strConnstring = "Provider=ADsDSOObject"
    strWQL = "SELECT * FROM 'LDAP://" & varConfigNC & _
        "' WHERE objectCategory= 'Computer' and OperatingSystem = 'Windows*Server*'"
    objRecordSet.Open strWQL, strConnstring
    If mode = "COUNT" Then
        Do Until objRecordSet.EOF
            retval = retval + 1
            objRecordSet.MoveNext
        Loop
        wscript.echo "Servers......: " & retval
    Else
        Do until objRecordSet.EOF
            Set objServer = GetObject(objRecordSet.Fields.Item(0))
            strServerName = objServer.CN
            strOperatingSystem = objServer.OperatingSystem
            wscript.echo strServerName & vbTab & strOperatingSystem
            objRecordSet.MoveNext
            Set objServer = Nothing
        Loop
    End If
    objRecordSet.Close
    Set objRecordSet = Nothing
End Sub

'----------------------------------------------------------------

Sub EnumComputers(mode)
    wscript.echo vbCRLF & "# enumerating computer objects..." & vbCRLF
    Dim retval, objConnection, objCommand, objRecordSet
    Dim c2000, cXP, cVista, cWin7, cNT, cOther, os
    retval = 0
    c2000 = 0
    cXP = 0
    cVista = 0
    cWin7 = 0
    cNT = 0
    cOther = 0
    Set objConnection = CreateObject("ADODB.Connection")
    Set objCommand =   CreateObject("ADODB.Command")
    objConnection.Provider = "ADsDSOObject"
    objConnection.Open "Active Directory Provider"
    Set objCOmmand.ActiveConnection = objConnection
    objCommand.CommandText = "Select Name, operatingSystem from 'LDAP://" & _
        LDAP_DN & "' where objectClass='computer' and OperatingSystem <> 'Windows*Server*'"
    objCommand.Properties("Page Size") = 1000
    objCommand.Properties("Timeout") = 30
    objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
    objCommand.Properties("Cache Results") = False
    Set objRecordSet = objCommand.Execute
    objRecordSet.MoveFirst
    If mode = "COUNT" Then
        Do Until objRecordSet.EOF
            retval = retval + 1
            objRecordSet.MoveNext
        Loop
        wscript.echo "Computers....: " & retval
    Else
        Do Until objRecordSet.EOF
            os = Trim(objRecordSet.Fields("operatingSystem").Value)
            wscript.echo "Computer.....: " & objRecordSet.Fields("Name").Value & _
                vbTab & os
            Select Case os
                Case "Windows 2000 Professional":
                    c2000 = c2000 + 1
                Case "Windows XP Professional":
                    cXP = cXP + 1
                Case "Windows NT":
                    cNT = cNT + 1
                Case Else:
                    If Left(os, 13) = "Windows Vista" Then
                        cVista = cVista + 1
                    ElseIf Left(os, 9) = "Windows 7" Then
                        cWin7 = cWin7 + 1
                    Else
                        cOther = cOther + 1
                    End If
            End Select
            objRecordSet.MoveNext
        Loop
        wscript.echo "# operating system types..."
        wscript.echo "WinNT........: " & cNT
        wscript.echo "Win2000......: " & c2000
        wscript.echo "WinXP........: " & cXP
        wscript.echo "WinVista.....: " & cVista
        wscript.echo "Win7.........: " & cWin7
        wscript.echo "Other........: " & cOther
    End If
End Sub

'----------------------------------------------------------------

Sub EnumUsers(mode)
    wscript.echo vbCRLF & "# enumerating user account objects..." & vbCRLF
    Dim retval, objConnection, objCommand, objRecordSet
    retval = 0
    Set objConnection = CreateObject("ADODB.Connection")
    Set objCommand =   CreateObject("ADODB.Command")
    objConnection.Provider = "ADsDSOObject"
    objConnection.Open "Active Directory Provider"
    Set objCOmmand.ActiveConnection = objConnection
    objCommand.CommandText = "Select Name, displayName from 'LDAP://" & _
        LDAP_DN & "' where objectCategory='person' and objectClass='user'"
    objCommand.Properties("Page Size") = 1000
    objCommand.Properties("Timeout") = 30
    objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
    objCommand.Properties("Cache Results") = False
    Set objRecordSet = objCommand.Execute
    objRecordSet.MoveFirst
    If mode = "COUNT" Then
        Do Until objRecordSet.EOF
            retval = retval + 1
            objRecordSet.MoveNext
        Loop
        wscript.echo "UserAccounts.: " & retval
    Else
        Do Until objRecordSet.EOF
            wscript.echo "UserAccount..: " & objRecordSet.Fields("Name").Value & _
                vbTab & objRecordSet.Fields("displayName").Value
            objRecordSet.MoveNext
        Loop
    End If
End Sub

'----------------------------------------------------------------

Sub EnumContacts(mode)
    wscript.echo vbCRLF & "# enumerating contact objects..." & vbCRLF
    Dim retval, objConnection, objCommand, objRecordSet
    retval = 0
    Set objConnection = CreateObject("ADODB.Connection")
    Set objCommand =   CreateObject("ADODB.Command")
    objConnection.Provider = "ADsDSOObject"
    objConnection.Open "Active Directory Provider"
    Set objCOmmand.ActiveConnection = objConnection
    objCommand.CommandText = "Select Name, displayName from 'LDAP://" & _
        LDAP_DN & "' where objectCategory='person' and objectClass='contact'"
    objCommand.Properties("Page Size") = 1000
    objCommand.Properties("Timeout") = 30
    objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
    objCommand.Properties("Cache Results") = False
    Set objRecordSet = objCommand.Execute
    objRecordSet.MoveFirst
    If mode = "COUNT" Then
        Do Until objRecordSet.EOF
            retval = retval + 1
            objRecordSet.MoveNext
        Loop
        wscript.echo "Contacts.....: " & retval
    Else
        Do Until objRecordSet.EOF
            wscript.echo "Contact......: " & objRecordSet.Fields("Name").Value & _
                vbTab & objRecordSet.Fields("displayName").Value
            objRecordSet.MoveNext
        Loop
    End If
End Sub

'----------------------------------------------------------------

Sub EnumGroups(mode)
    wscript.echo vbCRLF & "# enumerating security group objects..." & vbCRLF
    Dim retval, objConnection, objCommand, objRecordSet
    retval = 0
    Set objConnection = CreateObject("ADODB.Connection")
    Set objCommand =   CreateObject("ADODB.Command")
    objConnection.Provider = "ADsDSOObject"
    objConnection.Open "Active Directory Provider"
    Set objCOmmand.ActiveConnection = objConnection
    objCommand.CommandText = "Select Name, displayName from 'LDAP://" & _
        LDAP_DN & "' where objectClass='group'"
    objCommand.Properties("Page Size") = 1000
    objCommand.Properties("Timeout") = 30
    objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
    objCommand.Properties("Cache Results") = False
    Set objRecordSet = objCommand.Execute
    objRecordSet.MoveFirst
    If mode = "COUNT" Then
        Do Until objRecordSet.EOF
            retval = retval + 1
            objRecordSet.MoveNext
        Loop
        wscript.echo "Groups.......: " & retval
    Else
        Do Until objRecordSet.EOF
            wscript.echo "Group........: " & objRecordSet.Fields("Name").Value & _
                vbTab & objRecordSet.Fields("displayName").Value
            objRecordSet.MoveNext
        Loop
    End If
End Sub

'----------------------------------------------------------------

Sub EnumPrinters(mode)
    wscript.echo vbCRLF & "# enumerating shared printer objects..." & vbCRLF
    Dim retval, objConnection, objCommand, objRecordSet
    retval = 0
    Set objConnection = CreateObject("ADODB.Connection")
    Set objCommand =   CreateObject("ADODB.Command")
    objConnection.Provider = "ADsDSOObject"
    objConnection.Open "Active Directory Provider"
    Set objCOmmand.ActiveConnection = objConnection
    objCommand.CommandText = "Select Name, driverName, description from 'LDAP://" & _
        LDAP_DN & "' where objectCategory='printQueue'"
    objCommand.Properties("Page Size") = 1000
    objCommand.Properties("Timeout") = 30
    objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
    objCommand.Properties("Cache Results") = False
    Set objRecordSet = objCommand.Execute
    objRecordSet.MoveFirst
    If mode = "COUNT" Then
'        Do Until objRecordSet.EOF
'            retval = retval + 1
'            objRecordSet.MoveNext
'        Loop
        wscript.echo "Printers.....: " & objRecordSet.Count
    Else
        Do Until objRecordSet.EOF
            wscript.echo "Printer......: " & objRecordSet.Fields("Name").Value & _
                vbTab & objRecordSet.Fields("driverName").Value & _
                vbTab & objRecordSet.Fields("description").Value
            objRecordSet.MoveNext
        Loop
    End If
End Sub

'----------------------------------------------------------------

Sub EnumShares(mode)
    wscript.echo vbCRLF & "# enumerating shares..." & vbCRLF
    Dim retval, objConnection, objCommand, objRecordSet
    retval = 0
    Set objConnection = CreateObject("ADODB.Connection")
    Set objCommand =   CreateObject("ADODB.Command")
    objConnection.Provider = "ADsDSOObject"
    objConnection.Open "Active Directory Provider"
    Set objCOmmand.ActiveConnection = objConnection
    objCommand.CommandText = "Select Name from 'LDAP://" & _
        LDAP_DN & "' where objectClass='volume'"
    objCommand.Properties("Page Size") = 1000
    objCommand.Properties("Timeout") = 30
    objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
    objCommand.Properties("Cache Results") = False
    Set objRecordSet = objCommand.Execute
    objRecordSet.MoveFirst
    If mode = "COUNT" Then
        Do Until objRecordSet.EOF
            retval = retval + 1
            objRecordSet.MoveNext
        Loop
        wscript.echo "Shares.......: " & retval
    Else
        On Error Resume Next
        Do While Not(objRecordSet.EOF)
            wscript.echo "Share........: " & objRecordSet.Fields("Name").Value
            retval = retval + 1
            objRecordSet.MoveNext
        Loop
        wscript.echo "Shares.......: " & retval
    End If
End Sub

'----------------------------------------------------------------

Sub EnumDisabledUsers(mode)
    wscript.echo vbCRLF & "# enumerating disabled user accounts..." & vbCRLF
    Dim retval, objConnection, objCommand, objRecordSet
    retval = 0
    Set objConnection = CreateObject("ADODB.Connection")
    objConnection.Open "Provider=ADsDSOObject;"
    Set objCommand = CreateObject("ADODB.Command")
    objCommand.ActiveConnection = objConnection
    objCommand.CommandText = _
        "<GC://" & LDAP_DN & ">;(objectCategory=User)" & _
            ";userAccountControl,distinguishedName;subtree" 
    Set objRecordSet = objCommand.Execute    
    If mode = "COUNT" Then
        Do Until objRecordset.EOF
            intUAC=objRecordset.Fields("userAccountControl")
            If intUAC AND ADS_UF_ACCOUNTDISABLE Then
                retval = retval + 1
            End If
            objRecordset.MoveNext
        Loop
        wscript.echo "disabled.....: " & retval
    Else
        Do Until objRecordset.EOF
            intUAC=objRecordset.Fields("userAccountControl")
            If intUAC AND ADS_UF_ACCOUNTDISABLE Then
                wscript.echo "disabled_user: " & objRecordset.Fields("distinguishedName").Value
                retval = retval + 1
            End If
            objRecordset.MoveNext
        Loop
        wscript.echo "disabled.....: " & retval
    End If
    objConnection.Close
End Sub

'----------------------------------------------------------------

Sub ShowSpecialUsers(mode)
    wscript.echo vbCRLF & "# enumerating special user account objects..." & vbCRLF
    Dim objConnection, objCommand, objRecordSet, retval
    retval = 0
    On Error Resume Next
    Set objConnection = CreateObject("ADODB.Connection")
    Set objCommand =   CreateObject("ADODB.Command")
    objConnection.Provider = "ADsDSOObject"
    objConnection.Open "Active Directory Provider"
    Set objCommand.ActiveConnection = objConnection
    objCommand.Properties("Page Size") = 1000
    objCommand.CommandText = _
        "<LDAP://" & LDAP_DN & ">;(&(objectCategory=User)" & _
            "(userAccountControl:1.2.840.113556.1.4.803:=65536));Name;Subtree" 
    Set objRecordSet = objCommand.Execute
    objRecordSet.MoveFirst
    If mode = "COUNT" Then
        Do Until objRecordSet.EOF
            retval = retval + 1
            objRecordSet.MoveNext
        Loop
        wscript.echo "SpecialUsers.: " & retval
    Else
        Do Until objRecordSet.EOF
            wscript.echo "SpecialUser..: " & objRecordSet.Fields("Name").Value
            retval = retval + 1
            objRecordSet.MoveNext
        Loop
        wscript.echo "SpecialUsers.: " & retval
    End If
End Sub

'----------------------------------------------------------------

Sub ShowRootDSEinfo()
    wscript.echo vbCRLF & "# DOMAIN ROOT-DSE PROPERTIES" & vbCRLF
    objRootDSE.GetInfo
    For i = 0 to objRootDSE.PropertyCount - 1
        Set strProp = objRootDSE.Item(i)
        wscript.echo strProp.Name & " "
        For each strPropval in strProp.Values
           wscript.echo "  " &  strPropval.CaseIgnoreString
        Next
    Next
End Sub

'----------------------------------------------------------------
' sub: (strServer=ServerName, strSite=MySite)
'----------------------------------------------------------------

Sub ShowConnections(strServer, strSite)
    Dim objNTDSCont, objConn, confNC, objDNWithBin
    confNC = objRootDSE.Get("configurationNamingContext")
    Set objNTDSCont = GetObject("LDAP://cn=NTDS Settings,cn=" & strServer & _
        ",cn=servers,cn=" & strSite & ",cn=sites," & confNC )
    objNTDSCont.Filter = Array("ntdsConnection")
    For each objConn in objNTDSCont
       If objConn.Get("options") = 0 Then
          wscript.echo vbTab & vbTab & "connection...: " & objConn.Get("name") & " (MANUAL)"
       Else
          wscript.echo vbTab & vbTab & "connection...: " & objConn.Get("name") & " (AUTO)"
       End If
       wscript.echo vbTab & vbTab & vbTab & "enabled......: " & objConn.enabledConnection
       wscript.echo vbTab & vbTab & vbTab & "from.........: " & _

         Split(objConn.fromServer, ",")(1)
'       wscript.echo vbTab & vbTab & vbTab & "transport....: " & _

'         Split(objConn.transportType, ",")(0)
       wscript.echo vbTab & vbTab & vbTab & "cname........: " & objConn.Get("cn")
       For Each objDNWithBin In objConn.GetEx("ms-DS-ReplicatesNCReason")
           wscript.echo vbTab & vbTab & vbTab & "name_context.: " & objDNWithBin.DNString
       Next

    Next
End Sub

'----------------------------------------------------------------

Sub ShowBridgeHeadTransports(strServer, strSite)
    On Error Resume Next
    Set objServer = GetObject("LDAP://CN=" & strServer & _
        ",CN=Servers,CN=" & strSite & ","  & _
        " CN=Sites,CN=Configuration," & LDAP_DN)
    dnBHTList = objServer.GetEx("bridgeheadTransportList")
    For Each dnValue in dnBHTList
        wscript.echo vbTab & vbTab & "trn-protocol.: " & dnValue
    Next
End Sub

'----------------------------------------------------------------
' sub: (ldapPath = LDAP://OU=Sales,DC=domain,DC=com)
'----------------------------------------------------------------

Sub ShowOU_GPO_Info(ldapPath)
    On Error Resume Next
    Set objContainer = GetObject(ldapPath)
    wscript.echo vbCRLF & "# OU GPO PROPERTIES: " & ldapPath & vbCRLF
    strGpLink = objContainer.Get("gPLink")
    intGpOptions = objContainer.Get("gPOptions")

    If strGpLink <> " " Then
        'wscript.echo "gplink..: " & strGpLink
        arrGpLinkItems = Split(strGpLink,"]")
        For i = UBound(arrGPLinkItems) to LBound(arrGpLinkItems) + 1 Step -1
            arrGPLink = Split(arrGpLinkItems(i-1),";")
            strDNGPLink = Mid(arrGPLink(0),9)
            wscript.echo "gpo_link: " & strDNGPLink
            wscript.echo "gpo_name: " & GetGPOName(strDNGPLink)
            Select Case arrGPLink(1)
                Case 0
                    wscript.echo "No Override is cleared and the GPO is enabled."
                Case 1
                    wscript.echo "No Override is cleared and the GPO is disabled."
                Case 2
                    wscript.echo "No Override is checked and the GPO is enabled."
                Case 3
                    wscript.echo "No Override is checked and the GPO is disabled."
            End Select
          Next
    End If

    If intGpOptions = 1 Then
      wscript.echo "Block Policy Inheritance is checked."
    Else
      wscript.echo "Block Policy Inheritance is not checked."
    End If
End Sub

'----------------------------------------------------------------
' function: return NAME of a GPO
'----------------------------------------------------------------

Function GetGPOName(strDNGPLink)
    Set objConnection = CreateObject("ADODB.Connection") 
    objConnection.Open "Provider=ADsDSOObject;"  

    Set objCommand = CreateObject("ADODB.Command")
    objCommand.ActiveConnection = objConnection

    objCommand.CommandText = ";;distinguishedName,displayName;onelevel"
    Set objRecordSet = objCommand.Execute

    While Not objRecordSet.EOF
        If objRecordSet.Fields("distinguishedName") = strDNGPLink Then
          GetGPOName = objRecordSet.Fields("displayName")
          objConnection.Close
          Exit Function
        End If
        objRecordSet.MoveNext
    Wend
    objConnection.Close
End Function

'----------------------------------------------------------------
' sub: display security rights applied to a given OU
'----------------------------------------------------------------

Sub EnumOU_ACL(ldapPath)
    Const SE_SACL_PROTECTED = &H2000
    Const ADS_SECURITY_INFO_OWNER = &H1
    Const ADS_SECURITY_INFO_GROUP = &H2
    Const ADS_OPTION_SECURITY_MASK =&H3
    Const ADS_SECURITY_INFO_DACL = &H4
    Const ADS_SECURITY_INFO_SACL = &H8
    Set objContainer = GetObject(ldapPath)
    objContainer.SetOption ADS_OPTION_SECURITY_MASK, ADS_SECURITY_INFO_OWNER _
      Or ADS_SECURITY_INFO_GROUP Or ADS_SECURITY_INFO_DACL _
      Or ADS_SECURITY_INFO_SACL
    Set objNtSecurityDescriptor = objContainer.Get("ntSecurityDescriptor")
    intNtSecurityDescriptorControl = objNtSecurityDescriptor.Control
    wscript.echo "Auditing Tab"
    WScript.StdOut.WriteLine "Allow inheritable auditing entries from" & _
      "the parent to "
    WScript.StdOut.Write "propogate to this object and all child objects "
    If (intNtSecurityDescriptorControl And SE_SACL_PROTECTED) Then
        wscript.echo "is disabled."
    Else
        wscript.echo "is enabled."
    End If
    wscript.echo vbCRLF
    Set objSacl = objNtSecurityDescriptor.SystemAcl
    DisplayAceInformation objSacl, "SACL"
End Sub

'----------------------------------------------------------------

Sub DisplayAceInformation(SecurityStructure, strType)
    Const ADS_ACETYPE_SYSTEM_AUDIT = &H2
    Const ADS_ACETYPE_SYSTEM_AUDIT_OBJECT = &H7

    intAceCount = 0
    For Each objAce In SecurityStructure
        strTrustee = Mid(objAce.Trustee,1,12)
        If StrComp(strTrustee, "NT AUTHORITY", 1) <> 0 Then
            intAceCount = intAceCount + 1
            wscript.echo strType & " permission entry: " & intAceCount
            wscript.echo "Name: " & objAce.Trustee

            intAceType = objAce.AceType
            wscript.echo "ACETYPE IS: " & intAceType
            If (intAceType = ADS_ACETYPE_SYSTEM_AUDIT or _
                intAceType = ADS_ACETYPE_SYSTEM_AUDIT_OBJECT) Then
                WScript.StdOut.Write "Type: Success or Failure Audit"
            Else
                WScript.StdOut.Write "Audit Type Unknown."
            End If
            ReadBitsInAccessMask(objAce.AccessMask)
            wscript.echo vbCRLF
        End If
    Next
End Sub

'----------------------------------------------------------------

Sub ReadBitsInAccessMask(AccessMask)
    Const ADS_RIGHT_DELETE = &H10000
    Const ADS_RIGHT_READ_CONTROL = &H20000
    Const ADS_RIGHT_WRITE_DAC = &H40000
    Const ADS_RIGHT_WRITE_OWNER = &H80000
    Const ADS_RIGHT_DS_CREATE_CHILD = &H1
    Const ADS_RIGHT_DS_DELETE_CHILD = &H2
    Const ADS_RIGHT_ACTRL_DS_LIST = &H4
    Const ADS_RIGHT_DS_SELF = &H8
    Const ADS_RIGHT_DS_READ_PROP = &H10
    Const ADS_RIGHT_DS_WRITE_PROP = &H20
    Const ADS_RIGHT_DS_DELETE_TREE = &H40
    Const ADS_RIGHT_DS_LIST_OBJECT = &H80
    Const ADS_RIGHT_DS_CONTROL_ACCESS = &H100

    wscript.echo vbCRLF & "Standard Access Rights"
    If (AccessMask And ADS_RIGHT_DELETE) Then _
        wscript.echo vbTab & "-Delete an object."
    If (AccessMask And ADS_RIGHT_READ_CONTROL) Then _
        wscript.echo vbTab & "-Read permissions."
    If (AccessMask And ADS_RIGHT_WRITE_DAC) Then _
        wscript.echo vbTab & "-Write permissions."
    If (AccessMask And ADS_RIGHT_WRITE_OWNER) Then _
        wscript.echo vbTab & "-Modify owner."

    wscript.echo vbCRLF & "Directory Service Specific Access Rights"
    If (AccessMask And ADS_RIGHT_DS_CREATE_CHILD) Then _
        wscript.echo vbTab & "-Create child objects."
    If (AccessMask And ADS_RIGHT_DS_DELETE_CHILD) Then _
        wscript.echo vbTab & "-Delete child objects."
    If (AccessMask And ADS_RIGHT_ACTRL_DS_LIST) Then _
        wscript.echo vbTab & "-Enumerate an object."
    If (AccessMask And ADS_RIGHT_DS_READ_PROP) Then _
        wscript.echo vbTab & "-Read the properties of an object."
    If (AccessMask And ADS_RIGHT_DS_WRITE_PROP) Then _
        wscript.echo vbTab & "-Write the properties of an object."
    If (AccessMask And ADS_RIGHT_DS_DELETE_TREE) Then _
        wscript.echo vbTab & "-Delete a tree of objects"
    If (AccessMask And ADS_RIGHT_DS_LIST_OBJECT) Then _
        wscript.echo vbTab & "-List a tree of objects."

    wscript.echo vbCRLF & "Control Access Rights"
    If (AccessMask And ADS_RIGHT_DS_CONTROL_ACCESS) + _
        (AccessMask And ADS_RIGHT_DS_SELF) = 0 Then
        wscript.echo "-None"
    Else
        If (AccessMask And ADS_RIGHT_DS_CONTROL_ACCESS) Then _
          wscript.echo vbTab & "-Extended access rights."
        If (AccessMask And ADS_RIGHT_DS_SELF) Then
          wscript.echo vbTab & "-Active Directory must validate a property "
          wscript.echo vbTab & " write operation beyond the schema definition "
          wscript.echo vbTab & " for the attribute."
        End If
    End If
End Sub

'----------------------------------------------------------------

Sub EnumGPOs()
    Dim objGPM, objGPMConstants, objGPMDomain, objGPMSearchCriteria
    Dim objGPOList, objGPO
    wscript.echo vbCRLF & "# GROUP POLICY OBJECTS" & vbCRLF
    On Error Resume Next
    Set objGPM = CreateObject("GPMgmt.GPM")
    If err.Number <> 0 Then
        wscript.echo "error.......: " & _

            "GPMC is not installed, unable to enumerate group policy objects"
        Exit Sub
    End If
    Set objGPMConstants = objGPM.GetConstants()
    Set objGPMDomain = objGPM.GetDomain(ADSI_DN, "", objGPMConstants.UseAnyDC)
    Set objGPMSearchCriteria = objGPM.CreateSearchCriteria
    Set objGPOList = objGPMDomain.SearchGPOs(objGPMSearchCriteria)
    For each objGPO in objGPOList
       wscript.echo "gpo_entity...: " & objGPO.DisplayName
    Next

    wscript.echo "gpo_count...: " & objGPOList.Count

End Sub

'----------------------------------------------------------------

Sub NetlogonShare()
    Dim strDCpath, strPath, objFolder, objFile
    wscript.echo vbCRLF & "# NETLOGON SHARE CONTENTS" & vbCRLF
    strDCpath = wshShell.ExpandEnvironmentStrings("%logonserver%")
    strPath = strDCpath & "\netlogon"   
    If objFSO.FolderExists(strPath) Then
        Set objFolder = objFSO.GetFolder(strPath)
        EnumFiles strPath
        For each objSub in objFolder.SubFolders
            EnumFiles strPath & "\" & objSub.Name
        Next
    End If
End Sub

'----------------------------------------------------------------
' sub:
'----------------------------------------------------------------

Sub EnumFiles(strFolderPath)
    wscript.echo "# enumerating files in " & strFolderPath
    If objFSO.FolderExists(strFolderPath) Then
        Set objFolder = objFSO.GetFolder(strFolderPath)
        For each objFile in objFolder.Files
            wscript.echo "file_info...: " & objFile.Name & vbTab & _
                objFile.DateLastModified & vbTab & objFile.Size
        Next
    Else
        wscript.echo "error.......: unable to connect to " & strFolderPath
    End If
End Sub

No comments: