VBS Script to Check Port Availability in Windows

11,270

Solution 1

So I found a script someone had made a while back. It uses netStat. Should work on just about any windows machine. I think I was blinded by my desire to use the WMI.

Sub PortMonitor (strCommand2)

  Set StdOut = WScript.StdOut
  Set objShell = CreateObject("WScript.Shell")
  set objScriptExec = objShell.Exec (strCommand2)

  strPingResults = LCase(objScriptExec.StdOut.ReadAll)

  if len (strPingResults) > 0 then
     WScript.Echo "Established!"
  End if
end Sub

Dim strcommand
strCommand = "cmd /C ""netStat -n |find ""127.0.0.1:1137"" | find ""ESTABLISHED"""""
Call PortMonitor (strCommand)

OP: http://www.experts-exchange.com/OS/Microsoft_Operating_Systems/Server/2003_Server/Q_27476065.html#

Solution 2

Use cmd.exe and netstat:

D:\ :: type openports.bat
@echo off
for /f "tokens=2" %%i in ('netstat -an -p tcp ^| findstr ABH') do (
        for /f "delims=: tokens=2" %%p in ("%%i") do (
                echo %%p
        )
)

D:\ :: openports.bat
80
135
445
...

Note that this works for the German version of netstat, which prints ABHÖREN; for the English one, it is probably something like LISTENING, so you'll have to replace the findstr ABH with the appropriate expression for English.

Solution 3

Slightly different :

Function PortIsOpen(port)
    PortIsOpen = False
    Set StdOut = WScript.StdOut
    Set objShell = CreateObject("WScript.Shell")
    Set objScriptExec = objShell.Exec("cmd /C ""netstat -ano -p tcp | find "":" & port & " "" "" ")
    strPingResults = objScriptExec.StdOut.ReadAll
    If Len(strPingResults) > 0 Then PortIsOpen = True
End Function

Msgbox PortIsOpen("135")
Share:
11,270
jscott
Author by

jscott

Graduate Research Assistant at Clemson University. Research interests are in distributed systems, parallel algorithms, parallel file systems, HPC file systems, and PVFS in particular.

Updated on June 04, 2022

Comments

  • jscott
    jscott almost 2 years

    I am trying to check preconditions for a certain piece of software. I have a set of scripts that goes through and checks for things such as disk space, memory availability, etc.

    I need to create a script that can check if certain ports are open and accessible. I am using the WMI to check other network configuration items, but cannot find any references to checking port availability.

    Anyone have any ideas where I can find a WMI construct to let me view and manage ports or any other ideas for how to structure a new script to check port availability?