Network Inventory (Visual Basic Script)

0

Hi, I have the following script for a network inventory, I have tried it but at the end of the procedure I put the name of the pc in the 3 columns, it does not throw me or the ip of the computers or MacAdress could help me find the solution.

Option Explicit
Dim Row, XL, WshShell, FileSystem, RegularExpression, Dummy, TheNVFile, 
TheLine
Dim Whacks, WhacksFound, WhacksPattern,  Flag, HostName, NBTable, 
PingReport, PingPattern
Dim IPAddress, MACPattern, MACAddress, Matches, TheMatch, Match, NBCommand, 
TheNBTFile
Dim IPCommand, TheIPFile, FileName, TheDate, Suggestion, Book

Const ForReading = 1
Row = 2

Set XL = WScript.CreateObject("Excel.Application")
Set WshShell = WScript.CreateObject("WScript.Shell")
Set FileSystem = CreateObject("Scripting.FileSystemObject")
Set RegularExpression = New RegExp

Dummy = WshShell.Popup ("Compilando inventario de red.  Por favor                 
espere...",1,"Utilidad para inventario de red",64)

Call BuildSpreadSheet()

WshShell.Run "Cmd.exe /c Net View > C:\Windows\Temp\NetViewList.txt", 2,True
Set TheNVFile = FileSystem.OpenTextFile("C:\Windows\Temp\NetViewList.txt",     ForReading, True)

Do While TheNVFile.AtEndOfStream <> True
TheLine = TheNVFile.ReadLine
Whacks = "\"
WhacksFound = FindPattern(TheLine, Whacks)
If WhacksFound Then
WhacksPattern = "\\\S*"
Flag = "1"
HostName = GetPattern(TheLine, WhacksPattern, Flag )
NBTable = GetNBTable(HostName)
MACPattern = "MAC Address = \S*"
Flag = "2"
MACAddress = GetPattern(NBTable, MACPattern, Flag )
PingReport = GetIPAddress(HostName)
PingPattern = "Reply from \S*"
Flag = "3"
IPAddress = GetPattern(PingReport, PingPattern, Flag )
IPAddress = Replace(IPAddress, ":", "")
Call AddToSpreadSheet(HostName, IPAddress, MACAddress)
End If
Loop

TheNVFile.Close
FileSystem.DeleteFile("C:\Windows\Temp\NetViewList.txt")
Dummy = WshShell.Popup ("Inventario de red completado",5,"Utilidad para             inventario de red",64 )
Call SaveSpreadSheet()
Wscript.Quit

Sub BuildSpreadSheet()
XL.Visible = True
Set Book = XL.WorkBooks.Add
XL.Columns(1).ColumnWidth = 20
XL.Columns(2).ColumnWidth = 20
XL.Columns(3).ColumnWidth = 20
XL.Cells(1, 1).Value = "Nombre Equipo"
XL.Cells(1, 2).Value = "Direccion IP"
XL.Cells(1, 3).Value = "Direccion MAC"
XL.Range("A1:C1").Select
XL.Selection.Font.Bold = True
XL.Selection.Font.Size = 12
End Sub

Sub AddToSpreadSheet(HostName, IPAddress, MACAddress)
XL.Cells(Row, 1).Value = HostName
XL.Cells(Row, 2).Value = IPAddress
XL.Cells(Row, 3).Value = MACAddress
Row = Row + 1
XL.Cells(Row, 1).Select
End Sub
Sub SaveSpreadSheet()
TheDate = Date
TheDate = Replace(TheDate, "/", "-")
Suggestion = "NetAI " & TheDate & ".xls"
FileName = XL.GetSaveAsFilename(Suggestion)
If FileName <> False Then
Book.SaveAs(FileName)
End If
End Sub

Function FindPattern(TheText, ThePattern)
RegularExpression.Pattern = ThePattern
If RegularExpression.Test(TheText) Then
FindPattern = "True"
Else
FindPattern = "False"
End If
End Function

Function GetPattern(TheText, ThePattern, Flag)
RegularExpression.Pattern = ThePattern
Set Matches = RegularExpression.Execute(TheText)
For Each Match in Matches
TheMatch = Match.Value
If Flag = "1" Then TheMatch = Mid(TheMatch, 3)
If Flag = "2" Then TheMatch = Mid(TheMatch, 14)
If Flag = "3" Then TheMatch = Mid(TheMatch, 11)
Next
GetPattern = TheMatch
End Function

Function GetNBTable(HostName)
NBCommand = "nbtstat -a " & HostName
WshShell.Run "Cmd.exe /c " & NBCommand &" > C:\Windows\Temp\NBTList.txt",     2,True
Set TheNBTFile = FileSystem.OpenTextFile("C:\Windows\Temp\NBTList.txt",     ForReading, True)
GetNBTable = TheNBTFile.ReadAll
TheNBTFile.Close
FileSystem.DeleteFile("C:\Windows\Temp\NBTList.txt")
End Function

Function GetIPAddress(HostName)
IPCommand = "ping -n 1 " & HostName
WshShell.Run "Cmd.exe /c " & IPCommand &" > C:\Windows\Temp\IPList.txt", 2,True
Set TheIPFile = FileSystem.OpenTextFile("C:\Windows\Temp\IPList.txt",     ForReading, True)
GetIPAddress = TheIPFile.ReadAll
TheIPFile.Close
FileSystem.DeleteFile("C:\Windows\Temp\IPList.txt")
End Function
    
asked by Nelson 18.11.2017 в 13:02
source

1 answer

0

ADDRESSES

First of all we must obtain in some way the directions to which to connect, this can be obtained in several ways.

By the Active Directory of the domain:

For this sure there are simpler ways, but I used this one time, it worked, and I always use it, it consists in "extracting" the domain from your PC, connect to your active directory and extract the "Computer" 's:

Set objRoot = GetObject("LDAP://RootDSE")               'Objeto local de la cual se extrae el dominio
strDefaultDomainName = objRoot.Get("DefaultNamingContext")      'Extraccion de dominio
Set objRoot = Nothing                           'Vacio el objeto local.
CortstrDefaultDomainName = Split(strDefaultDomainName, "DC=")
CortstrDefaultDomainName2 = Split(CortstrDefaultDomainName(1), ",")
set Dominio = GetObject( "WinNT://" & CortstrDefaultDomainName2(0))     'Objeto, reprecenta al active directory del dominio.
For Each child in Dominio                           'Recorro los objetos del Objeto-Dominio
    If child.Class = "Computer" then                    'Si el objeto resulta ser de la clase "Computer" (computadora)
        Computer = child.Name
        Do
            Err.Clear()
            On Error Resume Next 'Ignoro errores
            'CONEXION
            If Err.Number <> 0 Then Exit Do End If 'Para ir al siguiente ciclo del for, devido al error
            On Error GoTo 0     'Dejo de ignorar errores
            'OBTENCION DE DATOS
            'REGISTRO DE DATOS
        Loop While False
    End If
Next

By IP to "Brute Force":

This consists of the never-weighted technique of For Each's nested, it would be at best something like this:

For A = 1 To 255
    For B = 1 To 255
        For C = 1 To 255
            For D = 1 To 255
                Computer = CStr(A) & "." & CStr(B) & "." & CStr(C) & "." & CStr(D)
                Do
                    Err.Clear()
                    On Error Resume Next 'Ignoro errores
                    'CONEXION
                    If Err.Number <> 0 Then Exit Do End If 'Para ir al siguiente ciclo del for, debido al error
                    On Error GoTo 0     'Dejo de ignorar errores
                    'OBTENCION DE DATOS
                    'REGISTRO DE DATOS
                Loop While False
            Next
        Next
    Next
Next

Either you can be sure that you are in a private network and / or you use known "Subnets" and therefore it would be somewhat shorter:

Subredes=Array(0,1,210) 
For Each C In Subredes
    For D = 1 To 255
        Computer = "192.168." & CStr(C) & "." & CStr(D)
        Do
            Err.Clear()
            On Error Resume Next 'Ignoro errores
            'CONEXION
            If Err.Number <> 0 Then Exit Do End If 'Para ir al siguiente ciclo del for, devido al error
            On Error GoTo 0     'Dejo de ignorar errores
            'OBTENCION DE DATOS
            'REGISTRO DE DATOS
        Loop While False
    Next
Next

By "External links":

This can be from the execution of a tool to the simple reading of a text file, the generic version would be like this:

WScript.CreateObject("WScript.Shell").Run "Cmd.exe /c Net View > C:\Windows\Temp\NetViewList.txt", 2, False, -2
Set objTextFile = FileSystem.OpenTextFile("C:\Windows\Temp\NetViewList.txt", 1)
Do Until objTextFile.AtEndOfStream      'Until es como While Not
    Linea = Trim(objTextFile.readline)
    If Asc(Linea) = -15441 Or Asc(Linea) = 239 Then Linea = Mid(Linea,4) End If  'Para eliminar el pocible caracter "BOM"
    Computer = Linea
    'Formatear "Computer" '(esto depende del "formato" del archivo)
    Do
        Err.Clear()
        On Error Resume Next
        'Conexion
        If Err.Number <> 0 Then Exit Do End If 'Para ir al siguiente ciclo del for, devido al error
        On Error GoTo 0
        'OBTENCION DE DATOS
        'REGISTRO DE DATOS
    Loop While False
Loop

CONNECTION

In all cases we will have a "ForEach base" which will provide us with a connection address (Computer). With this we will establish the connection to the Windows Management Instrumentation ( Windows Management Instrumentation or WMI for short). Through this connection we access the WMI Services.

If your current user (of execution) has the administrative permissions on the computers to connect you (normally, if you are a domain administrator), The way to connect would be the following:

Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\" & Computer & "\root\cimv2") 'Obviamente tenemos la variable "Computer" gracias al proceso mostrado anteriormente. (Puedes eliminar el "{impersonationLevel=impersonate}!" si no realizas "configuraciones delicadas".. o en este caso es innecesario dado que no vas a configurar nada sino solo consultar.

Otherwise, if you create a user that can connect to the computers, but it is not the one that executes the script, the method to connect would be the following:

UserAndDomain = ".\Administrator" 'Account WITH domain "\"
Pass = "" 'Account Password
Set objSWbemLocator = CreateObject("WbemScripting.SWbemLocator")
Set objWMIService = objSWbemLocator.ConnectServer(Computer, "Root\CIMv2", UserAndDomain , Pass)
objWMIService.Security_.ImpersonationLevel = 3 'Esto es para añadir privilegios, al igual que el caso anterior, puede omitirse esta linea.

DATA OBTAINING

Once we have obtained the WMI services object (objWMIService), we will highlight the queries WMI , over classes and instances of classes. The WMI queries will allow us to access (and if necessary configure) the different properties of the classes consulted, in this case, checking the classes instances Win32_NetworkAdapterConfiguration is required, other information such as the name of the PC and the user logged in, such as free hard disk space up to the resolution of the screen
can be obtained through Win32_ComputerSystem , Win32_LogicalDisk , Win32_DesktopMonitor respectively. For the conformation of the collections of classes returned by the WMI queries, the only way to go through them is (regardless of whether the collection is one or more elements) is the For Each. The following code shows a query in the following way:

Set colNetAdapters = objWMIService.ExecQuery("Select * from Win32_NetworkAdapterConfiguration where IPEnabled=TRUE") 'El Where aqui identifica la coneccion "activa"
For Each objNetAdapter in colNetAdapters
    Mac = objNetAdapter.MACAddress 'La direccion Mac
    IP = objNetAdapter.IPAddress(0) 'La direccion IP (es un array, tomo el primer objeto "0" del mismo)
    'IPX = objNetAdapter.IPXAddress 'Si tiene...
Next

DATA RECORD

At this point we have the data stored (the way you want, independent variables, arrays, data structures, etc. is your decision). Here you either use the Exel application object, or you dump it into a plain text file in CSV format, or whatever you want. I was going to expand on this point but it is clear that you understand the concept.

    
answered by 14.05.2018 / 19:07
source