Posted By

RobertHirabayashi on 02/10/12


Tagged

directory crawler DNS ip active sites ad static servers Workstations


Versions (?)

QueryDNSEnries-AllWindowsCrawler.vbs


 / Published in: Visual Basic
 

This script, building on my AllWindowsCrawler snippet, records DNS server entries (up to 3) as well as the IP Address and AD site location for a given Server (the AllWindows portion is commented out). This query is filtered to select only IP enabled adapters with DHCP disabled (i.e. static IP). The results are written to a CSV file.

  1. On Error Resume Next
  2.  
  3. Call Payload()
  4.  
  5. WScript.Echo "Done"
  6.  
  7. '*****************************************************************************************************************************************************
  8.  
  9. Function Payload()
  10.  
  11. Set ofsout = CreateObject("Scripting.FileSystemObject")
  12. Set readout = ofsout.OpenTextFile("C:\VB Script\" & OutPutFileName("","csv"),2,true)
  13.  
  14. readout.writeline "Server Name,AD Site Name,IP Address,DNS Server 1,DNS Server 2,DNS Server 3,"
  15.  
  16. On Error Resume Next
  17.  
  18. Const wbemFlagReturnImmediately=&h10
  19. Const wbemFlagForwardOnly=&h20
  20. Const ADS_SCOPE_SUBTREE = 2
  21.  
  22. ' Determine DNS domain name from RootDSE object.
  23. Set objRootDSE = GetObject("LDAP://RootDSE")
  24. strDNSDomain = objRootDSE.Get("defaultNamingContext")
  25.  
  26. ' Use ADO to search Active Directory for all computers.
  27. Set adoCommand = CreateObject("ADODB.Command")
  28. Set adoConnection = CreateObject("ADODB.Connection")
  29. adoConnection.Provider = "ADsDSOObject"
  30. adoConnection.Open "Active Directory Provider"
  31. adoCommand.ActiveConnection = adoConnection
  32.  
  33. ' Search entire domain.
  34. strBase = "<LDAP://" & strDNSDomain & ">"
  35.  
  36. ' Filter on computer objects with server operating system.
  37. ' Uncomment this line to get all computers in a domain
  38. 'strFilter = "(&(objectCategory=computer))"
  39. strFilter = "(&(objectCategory=computer)(operatingSystem=*server*))"
  40.  
  41. ' Comma delimited list of attribute values to retrieve.
  42. strAttributes = "cn"
  43.  
  44. ' Construct the LDAP syntax query.
  45. strQuery = strBase & ";" & strFilter & ";" & strAttributes & ";subtree"
  46.  
  47. adoCommand.CommandText = strQuery
  48. adoCommand.Properties("Page Size") = 1000
  49. adoCommand.Properties("Timeout") = 30
  50. adoCommand.Properties("Cache Results") = False
  51. adoCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
  52.  
  53. Set adoRecordset = adoCommand.Execute
  54.  
  55. ' Enumerate computer objects with server operating systems.
  56. Do Until adoRecordset.EOF
  57. strComputer = adoRecordset.Fields("cn").Value
  58.  
  59. WScript.Echo "Checking " & strComputer
  60. If IsHostAlive(strComputer) = True Then
  61. Wscript.Echo "Processing: " & strComputer
  62.  
  63. Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
  64.  
  65. Set colItems = objWMIService.ExecQuery("SELECT DNSServerSearchOrder, Description, IPAddress FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True AND DHCPEnabled = false")
  66.  
  67. For Each objItem in colItems
  68. DNSConfiguration = Join(objItem.DNSServerSearchOrder, ",")
  69.  
  70. IPAddress = objItem.IPAddress(0)
  71.  
  72. strSiteName = SiteName(IPAddress)
  73.  
  74. if LEN(DNSConfiguration)>1 THEN
  75. wscript.echo "Site Name: " & SiteName & vbcrlf
  76. 'wscript.echo strComputer & "," & objItem.IPAddress(0) & "," & DNSConfiguration
  77. 'readout.writeline strComputer & "," & objItem.IPAddress(0) & "," & DNSConfiguration & "," ' & vbcrlf
  78. wscript.echo "Computer Name: " & strComputer & vbCrLf & "Site Name: " & strSiteName & vbCrLf & "IpAddresses: " & IPAddress & vbCrLf & "DNS Servers: " & DNSConfiguration
  79. readout.writeline strComputer & "," & strSiteName & "," & IPAddress & "," & DNSConfiguration & "," ' & vbcrlf
  80. end if
  81. Next
  82.  
  83. 'Close queries
  84. Set objWMIService = Nothing
  85. Set colItems = Nothing
  86. Else
  87. wscript.echo "ERROR: " & strComputer & " cannot be reached or the account doesn't have proper permissions"
  88. End If
  89. 'End IF
  90. adoRecordset.MoveNext
  91. Loop
  92.  
  93. ' Clean up.
  94. adoRecordset.Close
  95. adoConnection.Close
  96.  
  97. 'Close Files
  98. readout.close()
  99.  
  100. 'Function Complete
  101.  
  102. End Function
  103.  
  104. '*****************************************************************************************************************************************************
  105.  
  106.  
  107. Function SiteName(IPAddr)
  108. '------------------------------------------------------------------------------'
  109. ' Displays the AD Site name for the supplied dotted decimal IP address.
  110. ' http://www.pcreview.co.uk/forums/determine-active-directory-site-given-ip-address-t1447992.html
  111. '------------------------------------------------------------------------------'
  112. ' IP2Site.vbs witten April 4, 2003 by Wayne Tilton
  113. '------------------------------------------------------------------------------'
  114.  
  115. Dim ConfigNameContext
  116. Dim DecIPAddr, MaskBits, NumAddrs, LoIPAddr, HiIPAddr, SiteAddrs
  117. Dim SubnetContainer, LDAPQry, Subnet
  118. Dim AdConn, AdComm, AdRS
  119.  
  120. SiteName = "Default-First-Site-Name" ' Default site name if no matches
  121. DecIPAddr = Dot2Dec(IPAddr) ' Convert supplied address to decimal
  122.  
  123. ConfigNameContext = GetObject("LDAP://RootDSE").Get("configurationNamingContext")
  124. SubnetContainer = "CN=Subnets,CN=Sites," & ConfigNameContext
  125. LDAPQry = "<LDAP://" & SubnetContainer & ">;(objectCategory=subnet);cn,siteObject"
  126.  
  127. Set AdConn = CreateObject("ADODB.Connection") ' Get an ADO connection object
  128.  
  129. AdConn.Provider = "ADsDSOObject" ' Set provider name
  130. AdConn.Open "Active Directory Provider" ' open connection
  131.  
  132. Set AdComm = CreateObject("ADODB.Command") ' Get an ADO command object
  133. Set AdComm.ActiveConnection = AdConn ' Tell command object about connection
  134. AdComm.Properties("SearchScope") = 2 ' we want to search everything
  135. AdComm.Properties("Page Size") = 500 ' and we want our records in lots of 500
  136.  
  137. AdComm.CommandText = LDAPQry ' Set the ADOCommandText
  138. Set AdRS = AdComm.Execute ' and run the query.
  139.  
  140. SiteAddrs = (2^31)-1 ' Really big range
  141. AdRS.MoveFirst ' Go to 1st record in the set
  142.  
  143. While Not AdRS.EOF ' Read 'em until they're gone
  144. Subnet = AdRs.Fields("cn") ' Get subnet name
  145. MaskBits = Split(Subnet,"/") ' Split IP addr from subnet mask
  146. NumAddrs = (2 ^ (32 - MaskBits(1))) - 1 ' Calc # addresses based on subnet mask
  147. LoIPAddr = Dot2Dec(MaskBits(0)) ' Get low end of IP range in decimal
  148. HiIPAddr = LoIPAddr + NumAddrs ' Calc high end of range by adding # add
  149.  
  150. ' Check to see if IP is within this subnet range and if so that it's smallest subnet with that addr
  151. If DecIPAddr => LoIPAddr And DecIPAddr <= HiIPAddr And NumAddrs <= SiteAddrs then
  152. SiteName = AdRs.Fields("siteObject")
  153. SiteName = GetObject("LDAP://" & AdRs.Fields("siteObject")).Get("name")
  154. Wscript.echo "Sitename: " & sitename
  155. SiteAddrs = NumAddrs ' Remember # addrs in this subnet
  156. End If
  157.  
  158. AdRS.MoveNext ' Go to next record or EOF
  159. Wend
  160.  
  161. Set AdRs = Nothing
  162. Set AdComm = Nothing
  163. Set AdConn = Nothing
  164. End Function
  165.  
  166.  
  167. Function IsHostAlive(strComputer)
  168. IsHostAlive = False ' normally we will return false, unless ping is successful
  169.  
  170. Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
  171. Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_PingStatus WHERE Address = '" + strComputer + "'")
  172.  
  173. For Each oRow In colItems
  174. Select Case oRow.StatusCode
  175. Case 0
  176. IsHostAlive = True
  177. wscript.echo strComputer & " is alive..."
  178. Case 11001 wscript.echo "Buffer Too Small"
  179. Case 11002 wscript.echo "Destination Net Unreachable"
  180. Case 11003 wscript.echo "Destination Host Unreachable"
  181. Case 11004 wscript.echo "Destination Protocol Unreachable"
  182. Case 11005 wscript.echo "Destination Port Unreachable"
  183. Case 11006 wscript.echo "No Resources"
  184. Case 11007 wscript.echo "Bad Option"
  185. Case 11008 wscript.echo "Hardware Error"
  186. Case 11009 wscript.echo "Packet Too Big"
  187. Case 11010 wscript.echo "Request Timed Out"
  188. Case 11011 wscript.echo "Bad Request"
  189. Case 11012 wscript.echo "Bad Route"
  190. Case 11013 wscript.echo "TimeToLive Expired Transit"
  191. Case 11014 wscript.echo "TimeToLive Expired Reassembly"
  192. Case 11015 wscript.echo "Parameter Problem"
  193. Case 11016 wscript.echo "Source Quench"
  194. Case 11017 wscript.echo "Option Too Big"
  195. Case 11018 wscript.echo "Bad Destination"
  196. Case 11032 wscript.echo "Negotiating IPSEC"
  197. Case 11050 wscript.echo "General Failure"
  198. Case Else wscript.echo "Status code " & objPing.StatusCode & " - Unable to determine cause of failure."
  199. End Select
  200. Next
  201. End Function
  202.  
  203.  
  204. Function OutPutFileName(ScriptFileName, fileEXT)
  205. strFileDate = Year(Now) & pd(Month(Now),2) & pd(Day(Now),2) & "-" & pd(Hour(Now),2) & pd(Minute(Now),2) & pd(Second(Now),2)
  206.  
  207. If ScriptFileName = "" Then
  208. ScriptFileName = Left(WScript.ScriptName, Len(WScript.ScriptName) - 4)
  209. End If
  210.  
  211. OutPutFileName = ScriptFileName & "_" & strFileDate & "." & fileEXT
  212. End Function
  213.  
  214.  
  215. ' Returns the decimal value of a dotted decimal IP address
  216. Function Dot2Dec(IPAddress)
  217. Dim Octets
  218.  
  219. Octets = Split(IPAddress,".")
  220. Dot2Dec = (Octets(0)*(2^24)) + (Octets(1)*(2^16)) + (Octets(2)*(2^8)) + Octets(3)
  221. End Function
  222.  
  223.  
  224. 'Pad single digit numbers with leading zero
  225. Function pd(n, totalDigits)
  226. if totalDigits > len(n) then
  227. pd = String(totalDigits-len(n),"0") & n
  228. else
  229. pd = n
  230. end if
  231. End Function
  232.  
  233. '*****************************************************************************************************************************************************

Report this snippet  

You need to login to post a comment.