Link to home
Start Free TrialLog in
Avatar of yccdadmins
yccdadmins

asked on

Script to check if a tcp port status is "ESTABLISHED"

Greetings all,

I have been looking for some code to try and string together a script that will check if a tcp port status is "established".

We need to monitor several ports that one of our applications is using - if the port status is anything other than ESTABLISHED (as shown in Netstat -an) then we need an error message sent out to administrators.

Any leads would help...
Avatar of Maen Abu-Tabanjeh
Maen Abu-Tabanjeh
Flag of Jordan image

here is it with loop to check port status :

 VBScript source code

Function CheckPort(Byval Server,Byval Port)
Dim SockObject
set SockObject=CreateObject("MSWinsock.Winsock.1")
SockObject.Protocol=0 ' TCP
Call SockObject.Close
Call SockObject.Connect (Server,Port)
while ((SockObject.State=6) or (SockObject.State=3)) 'socket state <> connecting or connection pending
'do nothing
wend
if(SockObject.State=7) then ' if socket connected
msgbox "Port OPen"
elseif(SockObject.State=9)then' If Error
msgbox "error"
elseif(SockObject.State=0)then 'Closed
msgbox "connection refused"
end if
call SockObject.Close
set SockObject=nothing
End Function
Call CheckPort("Server",445)

Open in new window


but change port number 445 to any you want to monitor
Avatar of yccdadmins
yccdadmins

ASKER

Going through your post right now Jordannet - looks like you're checking for open ports?  I have four ports that an application uses.  I need to make sure they are "Established" as shown in Netstat -an.  When the status is not established I need an alert....
there is another way to use netstat to pass it to vbscript :



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
         'Do something
      End if
end Sub

Dim strcommand
strCommand = "cmd /C ""netStat -n |find ""10.10.10.10:21"" | find ""ESTABLISHED"""""

Call PortMonitor (strCommand)

Open in new window

Awesome!  I put in the following and tested it on my local system.  I got the message box telling me the port status is established!  Thanks!  Now all I have to do is figure out an "else that sends me an email when the port is anything other than established.....
ASKER CERTIFIED SOLUTION
Avatar of Maen Abu-Tabanjeh
Maen Abu-Tabanjeh
Flag of Jordan image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
==> "we need an error message sent out to administrators"

What type of message or delivery are you intending here?

Why not just do it all in a BAT script, like:

@echo off
netstat -an|findstr /r /c:"127\.0\.0\.1:1234 *ESTABLISHED">NUL || (
  echo Not Established
  REM "send" alert here
)

Open in new window

~bp
The following function works well to get all known ports below 1024.  If you add some filters (to check for "ESTABLISHED") it will do precisely what you need.  The Regex will need to be tweaked:

<#
	.AUTHOR
		Will Steele

	.DEPENDENCIES
		netstat.exe

	.DESCRIPTION
		This script demonstrates how to convert netstat output to Powershell objects.
	
	.EXAMPLE
		. 20111118-001.ps1
	
	.EXTERNALHELP
		None.
		
	.FORWARDHELPTARGETNAME
		None.
		
	.INPUTS
		None.
		
	.LINK
		None.
		
	.NAME
		20111118-001.ps1
		
	.NOTES
		Demo raw nestat -an output for reference: netstat -an.  Looking for bound TCP ports on Local Address below 1025.
		
	.OUTPUTS
		System.Object
		
	.PARAMETER ParameterName
		N/A.
	
	.SYNOPSIS
		Demo conversion of netstat output to PSObject.
#>

#requires -version 2.0
Set-StrictMode -Version 2.0

#region variables
#endregion variables

#region functions

	function Get-OpenKnownTCPPorts {
		# Declare variables with $null.
		$netstat = $regex = $null;
		
		# Set $openports to datatype of [System.Array].
		$open_TCP_ports = @();
		
		# Initialize $netstat with netstat.exe -an output.
		$netstat = netstat -an;
		
		# Initialize $regex with pattern to parse $netstat data.
		$regex = "\s*(\w+)\s+(\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b):(\d+)\s+(\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b):(\d+)\s+(\w+)"
		
		# Parse $netstat data.
		foreach($line in $netstat) {
			# Check line for $regex match
			if($line -match $regex) {
				# Check port to see if value is less than or equal to 1024 to identify well-known ports.
				if(([int] $matches[7] -le 1024) -and ($matches[1] -eq "TCP")) {
					# If $regex array contains valid port entry add to $openports array.
					if($open_TCP_ports -notcontains $Matches[7]) {
						$open_TCP_ports += [Int]::Parse($Matches[7]);
					}
				}
			}
		} 
		
		# Sort and return $openports array.
		$open_TCP_ports | Sort-Object;
	} # end function Get-OpenKnownTCPPorts

	# Put processing in single function, Main
	function Main {
		Get-OpenKnownTCPPorts
	} # end function Main

#endregion functions

#region scriptbody

	. Main

#endregion scriptbody

Open in new window