Solved

Script needed to collect information from multiple AD-Sites

Posted on 2007-03-22
6
268 Views
Last Modified: 2010-04-16
Script needed to collect information from multiple AD-Sites

thanks Chris

please finish if you have the time on getting this to a csv file
0
Comment
Question by:ZJY0021
  • 3
  • 2
6 Comments
 
LVL 21

Expert Comment

by:mcsween
ID: 18773504
What information do you want to collect?
0
 

Author Comment

by:ZJY0021
ID: 18773521
Chris-Dent has wrote a very complecated script and i am trying to give him more points than just the 500
0
 
LVL 70

Expert Comment

by:Chris Dent
ID: 18775213

Almost done. I'll have to delay finishing it off and testing it until tomorrow morning. Dinner and such are calling.

Chris
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 70

Expert Comment

by:Chris Dent
ID: 18778503

I've added some other bits and pieces into this in an attempt to cut down the time it takes to run.

However, even with these it's going to take a very long time to do everything. Because of this it's been very difficult to validate the results it's pulling back, so I figure it's probably easier to pass it onto you and let you have a play at the same time.

You must be an Administrator on any machine you're connecting to for the WMI query to work.

I haven't added continual feedback into the script, so you won't have much information about how it's getting on. If you want that the easiest place to put it is in the GetSystemInfo subroutine.



Option Explicit

' User Constants

Const FILE_NAME = "out.csv"

'
' Generic Subroutines
'

Sub GetConfiguredSubnets
      ' Populates Global Dictionary "objConfiguredSubnets" with Subnets
      ' entered under the Configuration Subtree of AD.

      Dim objRootDSE, objSubnets, objSubnet, objSite
      Dim strSubnets, strNetworkAddress, strSite
      Dim arrTemp
      Dim intMaskLength

      Set objRootDSE = GetObject("LDAP://RootDSE")
      strSubnets = "CN=Subnets,CN=Sites," & objRootDSE.GEt("configurationNamingContext")
      Set objRootDSE = Nothing

      Set objSubnets = GetObject("LDAP://" & strSubnets)
      For Each objSubnet in objSubnets
            arrTemp = Split(objSubnet.Get("name"), "/")
            strNetworkAddress = arrTemp(0)
            strNetworkAddress = strNetworkAddress
            
            ' Location (if completed on Subnet) can be Populated instead of Sitename with:
            ' On Error Resume Next
            ' strSite = "" : strSite = objSubnet.Get("location")
            ' On Error Goto 0

            On Error Resume Next
            Set objSite = GetObject("LDAP://" & objSubnet.Get("siteObject"))
            strSite = "" : strSite = objSite.Get("name")
            Set objSite = Nothing

            If Not objConfiguredSubnets.Exists(strNetworkAddress) Then
                  objConfiguredSubnets.Add strNetworkAddress, strSite
            End If
      Next
      Set objSubnets = Nothing
End Sub

'
' Generic Functions
'

Function PingHost(strHost)
      ' Return Type: Boolean
      ' Basic Ping Test. Returns true if host responds.
      
      Dim objShell, objScriptExec, objStdOut
      Dim strOut
      Dim booReply
      
      Set objShell = CreateObject("WScript.Shell")
      Set objScriptExec = objShell.Exec("ping -n 1 " & strHost)
      Set objStdOut = objScriptExec.StdOut
      
      booReply = False
      Do Until objStdOut.AtEndOfStream
            strOut = objStdOut.ReadLine
            If InStr(strOut, "Reply from ") Then
                  booReply = True
            End If
      Loop
      
      PingHost = booReply
      
      Set objStdOut = Nothing
      Set objScriptExec = Nothing
      Set objShell = Nothing
End Function

Function GetDNSAddresses(strComputerName)
      ' Return Type: Array
      ' Returns an Array containing each IP Address for a given Node Name from a
      ' DNS Query

      Dim objShell, objScriptExec, objStdOut
      Dim strIPAddress, strOut
      Dim arrIPAddresses

      Set objShell = CreateObject("WScript.Shell")
      Set objScriptExec = objShell.Exec("nslookup " & strComputerName)
      Set objStdOut = objScriptExec.StdOut
      
      strIPAddress = ""
      Do Until objStdOut.AtEndOfStream
            strOut = objStdOut.ReadLine
            If InStr(strOut, "Name:") Then
                  strIPAddress = objStdOut.ReadLine
      
                  If InStr(strIPAddress, "Address:") > 0 Then
                        strIPAddress = Trim(Replace(strIPAddress, "Address:", ""))
                  ElseIf InStr(strIPAddress, "Addresses:") > 0 Then
                        strIPAddress = Trim(Replace(strIPAddress, "Addresses:", ""))
                  End If
            End If
      Loop
      
      GetDNSAddresses = Split(strIPAddress, ", ")
      
      Set objStdOut = Nothing
      Set objScriptExec = Nothing
      Set objShell = Nothing
End Function

Function ConvertIPToBinary(strIP)
      ' Return Type: String
      ' Convert any IP Address into it's Binary representation

      Dim strOctet, strBinOctet, strBinIP
      Dim arrOctets
      Dim intTemp, i

      arrOctets = Split(strIP, ".")
      For Each strOctet in arrOctets
            intTemp  = 0
            strBinOctet = ""
            For i = 0 To 7
                  If intTemp + 2^(7 - i) <= CInt(strOctet) Then
                        strBinOctet = strBinOctet & "1"
                        intTemp = intTemp + 2^(7 - i)
                  Else
                        strBinOctet = strBinOctet & "0"
                  End If
            Next
            strBinIP = strBinIP & "." & strBinOctet
      Next
      ConvertIPToBinary = Right(strBinIP, Len(strBinIP) - 1)
End Function

Function GetNetworkAddress(strIP, intMaskLength)
      ' Return Type: String
      ' Calculate the Network Address for a given IP Address and Subnet Mask

      Dim strOctet, strBinOctet, strBinIP, strBinMask, strIPBit, strMaskBit
      Dim strBinNetwork, strNetworkAddress
      Dim i, intTemp, intOctet, intBit
      Dim arrOctets

      strBinIP = ConvertIPToBinary(strIP)

      For i = 1 to 32
            If i <= intMaskLength Then
                  strBinMask = strBinMask & "1"
            Else
                  strBinMask = strBinMask & "0"
            End If
            If i = 8 Or i = 16 Or i = 24 Then
                  strBinMask = strBinMask & "."
            End If
      Next

      For i = 1 to Len(strBinIP)
            strIPBit = Mid(strBinIP, i, 1)
            strMaskBit = Mid(strBinMask, i, 1)
            If strIPBit = "1" And strMaskBit = "1" Then
                  strBinNetwork = strBinNetwork & "1"
            ElseIf strIPBit = "." Then
                  strBinNetwork = strBinNetwork & strIPBit
            Else
                  strBinNetwork = strBinNetwork & "0"
            End If
      Next

      arrOctets = Split(strBinNetwork, ".")
      For Each strOctet in arrOctets
            intOctet = 0
            For i = 0 to 7
                  intBit = CInt(Mid(strOctet, i + 1, 1))
                  If intBit = 1 Then
                        intOctet = intOctet + 2^(7 - i)
                  End If
            Next
            strNetworkAddress = strNetworkAddress & "." & CStr(intOctet)
      Next
      GetNetworkAddress = Right(strNetworkAddress, Len(strNetworkAddress) - 1)
End Function

'
' Script Specific Subroutines
'

Sub GetComputersFromAD
      ' AD Query for Computer Objects. Filters out Server Objects.

      Const ADS_SCOPE_SUBTREE = 2

      Dim objConnection, objCommand, objRecordSet, objRootDSE
      Dim strComputer

      Set objConnection = CreateObject("ADODB.Connection")
      objConnection.Provider = "ADsDSOObject"
      objConnection.Open "Active Directory Provider"

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

      Set objRootDSE = GetObject("LDAP://RootDSE")
      objCommand.CommandText = "SELECT distinguishedName, name, operatingSystem " &_
            "FROM 'LDAP://" & objRootDSE.Get("defaultNamingContext") & "' WHERE objectClass='computer'"
      Set objRootDSE = Nothing

      objCommand.Properties("Page Size") = 1000
      objCommand.Properties("Timeout") = 600
      objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
      objCommand.Properties("Cache Results") = False

      Set objRecordSet = objCommand.Execute

      While Not objRecordSet.EOF
            If InStr(1, objRecordSet.Fields("operatingSystem"), "Server", VbTextCompare) = 0 Then
                  strComputer = objRecordSet.Fields("name")
                  GetSystemInfo strComputer
            End If
            objRecordSet.MoveNext
      Wend

      objConnection.Close

      Set objRecordSet = Nothing
      Set objCommand = Nothing
      Set objConnection = Nothing
End Sub

Sub GetSystemInfo(strComputer)
      ' Populates Global Dictionary "objComputers".

      Const WBEM_RETURN_IMMEDIATELY = &h10
      Const WBEM_FORWARD_ONLY = &h20

      Dim objWMIService, objItem
      Dim colCompSystem, colNetwork, colLogicalDisk
      Dim strUser, strIP, strIPAddress, strSubnet, strSite, strDrives, strDriveLetter, strShare, strType
      Dim intSubnet
      Dim arrTemp

      ' IP Address Test
      arrTemp = GetDNSAddresses(strComputer)
      If UBound(arrTemp) = -1 Then
            Exit Sub
      End If

      ' Basic Connectivity Test
      If PingHost(strComputer) = False Then
            Exit Sub
      End If

      ' Error Control for WMI Connection
      On Error Resume Next : Err.Clear
      Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMv2")
      If Err.Number = 0 Then
            ' Current User

            Set colCompSystem = objWMIService.ExecQuery("SELECT * FROM Win32_ComputerSystem",_
                  "WQL", WBEM_RETURN_IMMEDIATELY + WBEM_FORWARD_ONLY)
            strUser = ""
            For Each objItem in colCompSystem
                  strUser = objItem.UserName
            Next
            Set colCompSystem = Nothing

            ' Site Information
            arrTemp = GetDNSAddresses(strComputer)
            strIP = arrTemp(0)

            strSubnet = ""
            Set colNetwork = objWMIService.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration",_
                  "WQL", WBEM_RETURN_IMMEDIATELY + WBEM_FORWARD_ONLY)
            For Each objItem in colNetwork
                  If Not IsNUll(objItem.IPAddress) And objItem.IPEnabled = True Then
                        For Each strIPAddress in objItem.IPAddress
                              If strIPAddress <> "0.0.0.0" And strIPAddress <> "" Then
                                    If strIPAddress = strIP Then
                                          strSubnet = Join(objItem.IPSubnet)
                                    End If
                              End If
                        Next
                  End If
            Next
            Set colNetwork = Nothing

            strSite = ""
            If strSubnet <> "" Then
                  intSubnet = UBound(Split(ConvertIPToBinary(strSubnet), "1"))
                  If objConfiguredSubnets.Exists(GetNetworkAddress(arrTemp(0), intSubnet)) Then
                        strSite = objConfiguredSubnets(GetNetworkAddress(arrTemp(0), intSubnet))
                  End If
            End If

            ' Drive Information

            Set colLogicalDisk = objWMIService.ExecQuery("SELECT * FROM Win32_LogicalDisk",_
                  "WQL", WBEM_RETURN_IMMEDIATELY + WBEM_FORWARD_ONLY)

            strDrives = ""
            For Each objItem in colLogicalDisk
                  strDriveLetter = objItem.DeviceID

                  ' We need to test the value for DriveType to figure out what the drive actually is
                  strType = "" : strShare = ""
                  If objItem.DriveType = 3 Then
                        strType = "Fixed Drive"
                  ElseIf objItem.DriveType = 4 Then
                        strType = "Network Drive"
                        strShare = objItem.ProviderName
                  ElseIf objItem.DriveType = 5 Then
                        strType = "Removable Media / CD / DVD"
                  End If
                  If strType <> "" Then
                        strDrives = strDrives & ":" & strDriveLetter & ";" & strType & ";" & strShare
                  End If
            Next
            
            If Not objComputers.Exists(strComputer) Then
                  objComputers.Add strComputer, Array(strUser, strSite, strDrives)
            End If
      End If
      On Error Goto 0
End Sub

Sub WriteReport(strFileName)
      Dim objFileSystem, objFile
      Dim strComputer

      Set objFileSystem = CreateObject("Scripting.FileSystemObject")
      Set objFile = objFileSystem.OpenTextFile(strFileName, 2, True, 0)
      
      objFile.WriteLine "ComputerName,UserName,Site,Drives"
      
      For Each strComputer in objComputers
            objFile.WriteLine strComputer & "," & objComputers(strComputer)(0) & "," & objComputers(strComputer)(1) &_
                  "," & objComputers(strComputer)(2)
      Next
      
      Set objFile = Nothing
      Set objFileSystem = Nothing
End Sub

'
' Main Code Block
'

' Global Variables

Dim objConfiguredSubnets, objComputers

Set objConfiguredSubnets = CreateObject("Scripting.Dictionary")
GetConfiguredSubnets

Set objComputers = CreateObject("Scripting.Dictionary")
GetComputersFromAD

If objComputers.Count > 0 Then
      WriteReport FILE_NAME
End If

Set objConfiguredSubnets = Nothing
Set objComputers = Nothing
0
 

Author Comment

by:ZJY0021
ID: 18779800
wow chris is this the completed script  or an insert into what you have already done. sorryi am a little lost now :(

you are an awsome guy to do this.

thank you,
0
 
LVL 70

Accepted Solution

by:
Chris Dent earned 500 total points
ID: 18779928

It's a complete script, includes everything from before and a few other bits.

Chris
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Suggested Solutions

If you have done a reformat of your hard drive and proceeded to do a successful Windows XP installation, you may notice that a choice between two operating systems when you start up the machine. Here is how to get rid of this: Click Start Clic…
Not long ago I saw a question in the VB Script forum that I thought would not take much time. You can read that question (Question ID  (http://www.experts-exchange.com/Programming/Languages/Visual_Basic/VB_Script/Q_28455246.html)28455246) Here (http…
Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now