Search code examples
scriptingvbscriptwmiwmi-querynetstat

Netstat with WMI and VBScript


I am working on a project where I need to modify a script used for network documentation. The current script that we use is a modified version of SYDI, found here. What I would like to do is add to this script the ability to execute a netstat -an and have it returned with the rest of the report. I was curious if anyone has used WMI and VBScript to return netstat information and how it might be able to be incorporated into this script.

NOTE: I am not trying to promote a product and I am not affiliated with the SYDI project.


Solution

  • You could run netstat and capture the result like the script here under, but much info is also available from activeX but the i would need to know what information you need exactly.

    set sh = CreateObject("Wscript.Shell") 
    set Connections = CreateObject("Scripting.Dictionary") 
    
    call Main() 
    
    Function Main() 
        call GetConnections() 
        call ProcessConnections() 
    End Function 
    
    Function GetConnections() 
        i = 0 
        set shExec = sh.Exec("netstat -f") 
    
        Do While Not shExec.StdOut.AtEndOfStream 
            Line = shExec.StdOut.ReadLine() 
            If Instr(Line, "TCP") <> 0 Then 
                Set Connection = New NetworkConnection 
                Connection.ParseText(Line) 
                call Connections.Add(i, Connection) 
                i = i + 1 
            End If 
        Loop 
    End Function 
    
    Function ProcessConnections() 
        For Each ConnectionID in Connections.Keys 
            wscript.echo ConnectionID & Connections(ConnectionID).RemoteIP 
        Next 
    End Function 
    
    Class NetworkConnection 
        Public Protocol 
        Public LocalIP 
        Public LocalPort 
        Public RemoteIP 
        Public RemotePort 
    
        Public Sub ParseText(Line) 
            dim i 
    
            For i = 5 to 2 Step -1 
                Line = Replace(Line, String(i, " "), " ") 
            Next 
    
            Line = Replace(Line, ":", " ") 
            Line = Right(Line, Len(Line) - 1) 
            Line = Split(Line, " ") 
    
            Protocol = Line(0) 
            LocalIP = Line(1) 
            LocalPort = Line(2) 
            RemoteIP = Line(3) 
            RemotePort = Line(4) 
    
        End Sub 
    
        Private Sub Class_Initialize 
            'MsgBox "Initialized NetworkConnection object" 
        End Sub 
    
    End Class
    

    EDIT: based on the comment of OP here a simplified version

    set sh = CreateObject("Wscript.Shell")  
    call GetConnections()  
    
    Function GetConnections()  
      i = 0  
      set shExec = sh.Exec("netstat -an")  
       Do While Not shExec.StdOut.AtEndOfStream  
          Wscript.Echo shExec.StdOut.ReadLine()  
      Loop  
    End Function