We help IT Professionals succeed at work.

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

yccdadmins
yccdadmins asked
on
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...
Comment
Watch Question

Maen Abu-TabanjehNetwork Administrator, Network Consultant
Top Expert 2011

Commented:
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

Author

Commented:
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....
Maen Abu-TabanjehNetwork Administrator, Network Consultant
Top Expert 2011

Commented:
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

Author

Commented:
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.....
Network Administrator, Network Consultant
Top Expert 2011
Commented:
here is the script .. now give me the full mark :

Set objShell = CreateObject("WScript.Shell")
strComputerName = objShell.ExpandEnvironmentStrings("%computername%")
 
strCommand = "%comspec% /c netstat -a -n | find /C ""TCP"""
Set objWshScriptExec = objShell.Exec(strCommand)
Set objStdOut = objWshScriptExec.StdOut
intOutput = CInt(objStdOut.ReadLine)
 
intThreshold = 5000
strEmailFrom = "DoNotReply@yourdomain.com"
strEmailTo = "user@yourdomain.com"
strEmailSubject = "TCP connection threshold exceeded on " & strComputerName
strEmailBody = CStr(intOutput) & " TCP connections are established on " & strComputerName
strSMTP = "smtpserver.yourdomain.com"
 
If intOutput > intThreshold Then
    Set objEmail = CreateObject("CDO.Message")
 
    objEmail.From = strEmailFrom
    objEmail.To = strEmailTo
    objEmail.Subject = strEmailSubject
    objEmail.Textbody = strEmailBody
    objEmail.Configuration.Fields.Item _
        ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
    objEmail.Configuration.Fields.Item _
        ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = _
            strSMTP
    objEmail.Configuration.Fields.Item _
        ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
    objEmail.Configuration.Fields.Update
 
    objEmail.Send
End If

Open in new window

Bill PrewTest your restores, not your backups...
Top Expert 2016

Commented:
==> "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

Commented:
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