Inicio Soporte Técnico VBScript – Crear inventario de red local automático en Excel

VBScript – Crear inventario de red local automático en Excel

4681
0

Cuando administramos una red y no llevamos un control o un inventario de equipos, IPs, etc. Si requerimos obtener estos datos rápidamente podemos crear un inventario de red local automático e ir complementando los datos faltantes y quizás corroborar alguna muestra de equipos.

Código VBScript para crear inventario de red local automático

Con el siguiente código podremos crear un inventario automático de los equipos de Red con los campos: Nombre de Equipo, Direccion IP y Direccion MAC, el cual nos lo guardara en una Hoja de Excel al finalizar el proceso.

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 ("Compiling Network Address Inventory.  Please Wait...",1,"Network Address Inventory Utility",64)

Call BuildSpreadSheet()

WshShell.Run "Cmd.exe /c Net View > C:WindowsTempNetViewList.txt", 2,True
Set TheNVFile = FileSystem.OpenTextFile("C:WindowsTempNetViewList.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:WindowsTempNetViewList.txt")
Dummy = WshShell.Popup ("Network Address Inventory Operation Complete",5,"Network Address Inventory Utility",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:WindowsTempNBTList.txt", 2,True
	Set TheNBTFile = FileSystem.OpenTextFile("C:WindowsTempNBTList.txt", ForReading, True)
	GetNBTable = TheNBTFile.ReadAll
	TheNBTFile.Close
	FileSystem.DeleteFile("C:WindowsTempNBTList.txt")
End Function

Function GetIPAddress(HostName)
	IPCommand = "ping -n 1 " & HostName
	WshShell.Run "Cmd.exe /c " & IPCommand &" > C:WindowsTempIPList.txt", 2,True
	Set TheIPFile = FileSystem.OpenTextFile("C:WindowsTempIPList.txt", ForReading, True)
	GetIPAddress = TheIPFile.ReadAll
	TheIPFile.Close
	FileSystem.DeleteFile("C:WindowsTempIPList.txt")
End Function

Crear archivo inventario de red local automático

Nota: Los equipos deben estar prendidos (Puede ser sin iniciar sesión)

  1. Abrimos un editor de texto como Notepad (recomendado Notepad++) copiamos el código del Script anterior y lo pegamos.
    Pegar en notepad++ el Código VBScript para crear inventario de red local automático
    Pegar en notepad++ el Código VBScript para crear inventario de red local automático
  2. Guardamos el archivo con un nombre que deseemos puede ser InventarioDeRed y con extensión .vbs
    Vb guardar notepad++
    Vb guardar notepad++
  3. Nos aparecerá un archivo como el siguiente el cual dando doble clic.
  4. En un principio veremos un cuadro de dialogo que indica que el proceso esta comenzando.
  5. Nos ejecutara Excel y una ventana de Command Prompt automáticamente donde comenzara a llenar con la información (Nombre del Equipo, Dirección IP y Dirección MAC).
  6. El proceso puede tardar algunos minutos dependiendo la cantidad de equipos existentes en la Red.
  7. Al finalizar el proceso nos va a aparecer la ventana Guardar Como (Save As).
Te recomendamos  Restablecer Microsoft Outlook a su configuración original / predeterminada

Información: Vamos a percatarnos que existen algunos equipos que en los campos Direccion IP y Direccion MAC nos aparece el nombre del equipo en todos los campos o nos aparece la IP del equipo donde estamos ejecutando el script. Esto se debe a que el equipo se encuentra apagado o no se tiene respuesta del equipo puede ser por bloqueo del Firewall.