• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 949
  • Last Modified:

Verify a program accepts a connection through Port

I am working on a script using port query to monitor Port 23 on two remote PC's (both are VM). So far i have gotten the script to run pretty well, but there is a variable that I cannot seem to account for...

 The remote machines are basically running a telnet receiving program (a gateway) users connect to it via telnet session from various sources, desktop machine or wireless scanner. I have scheduled a task to run my script every 5 minutes, when the port is open it writes to a txt document, when it is closed it sends an email. But sometimes the port is open and the program is responding but users cannot connect to...

I have tried to catch that variable by watching the gateway's process, pinging the machine, reading the log files written by the gateway program... I am just out of ideas to catch it.

The log files capture the IP address and because I run this off my local machine I could query the log for my IP, but the date/time on that line need to match the connection/response time.


Any help/suggestions?
$date = (Get-Date).toString("M-dd-yy")
$time = (get-date).tostring("hh:mm")
$ChkFile = test-path C:\scripts\$date-log.txt
if($chkfile -eq $true){add-content $date-log.txt "$date $time new test"}
else{$record}
Get-ChildItem -Filter *.txt | Where {$_.name -ne ("$date-log.txt")}  | move-Item -destination c:\scripts\hist  -force
$pcname=@('111.111.1.11';'111.111.1.120')
foreach($p in $pcname){
portqry -n $p -nr -e 23 -q
if($LASTEXITCODE -eq 0){Add-content $date-log.txt "All good ($p)($date) ($time)"}
#Send email if error on port check from gateway
elseif($lastexitcode -eq 1){
$emailFrom = "AlertMonitor@domain.com"
$emailTo = "user@domain.com"
$subject = "Barcode Gateway Alert"
$body = "There is something wrong with $p it is not not responding. Last checked $date $time."
$smtpServer = "111.111.1.11"
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($emailFrom, $emailTo, $subject, $body)
$emailFrom = "AlertMonitor@domain.com"
$emailTo = "user@domain.com"
$subject = "Barcode Gateway Alert"
$body = "There is something wrong with $p it is not not responding. Last checked $date $time."
$smtpServer = "192.168.1.25"
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($emailFrom, $emailTo, $subject, $body)
}
elseif($lastexitcode -eq 2){
$emailFrom = "AlertMonitor@domain.com"
$emailTo = "user@domain.com"
$subject = "Barcode Gateway Alert"
$body = "There is something wrong with $p it is not not responding. Last checked $date $time."
$smtpServer = "111.111.1.11"
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($emailFrom, $emailTo, $subject, $body)
$emailFrom = "AlertMonitor@domain.com"
$emailTo = "usere@domain.com"
$subject = "Barcode Gateway Alert"
$body = "There is something wrong with $p it is not not responding. Last checked $date $time."
$smtpServer = "192.168.1.25"
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($emailFrom, $emailTo, $subject, $body)
}
}
#$record = New-Item –ItemType file "$date-log.txt" 

Open in new window

0
Dem-Tech
Asked:
Dem-Tech
  • 7
  • 6
1 Solution
 
Chris DentPowerShell DeveloperCommented:

> But sometimes the port is open and the program is responding but users cannot connect to...

The only way you'll find that out is by interacting with the program itself. Otherwise you'd have to see where it was failing on the client, is it accepting the connection but immediately dropping it?

Chris
0
 
Dem-TechAuthor Commented:
If I try to connect with a telnet session it never connects. If I ping the machine, I get a response. When I use portqry to check the status of the port, it returns 'listening".  When watching the "process" in task manager it shows as "responding".

Is there a way to use telnet in powershell?  
0
 
Chris DentPowerShell DeveloperCommented:
I've done one to form then drop a TCP connection before. Maybe worth a try?
Function Test-TcpPort {
  Param(
    [Net.IPAddress]$IPAddress,
    [UInt32]$Port
  )

  $TcpClient = New-Object Net.Sockets.TcpClient
  Try { $TcpClient.Connect($IPAddress, $Port) } Catch { }
  If ($?) {
    Write-Host "Connection succeeded"
    $TcpClient.Close()
  } Else {
    Write-Host "Connection Failed"
  }
}

# Use the function
Test-TcpPort "HostCIPAddress" 3389

Open in new window

Chris
0
Problems using Powershell and Active Directory?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

 
Dem-TechAuthor Commented:
I will give that a try. I will let you know what the result is... It quits accepting at random times, so it make take few hours.

Thank you,

0
 
Chris DentPowerShell DeveloperCommented:
No problem. If it helps we can have it return True or False instead of it using Write-Host, it'll be more useful that way.

Chris
0
 
Dem-TechAuthor Commented:
Chris,

I would love to be back this afternoon to report that the check was successful. But, I cannot.

The program/port just went in to hibernation, so I attempted the script that you wrote and the result was: connection succeeded.

I also ran the process monitor script that I wrote (see below), and the result of that was the same.

I also attempted to open a telnet connection to the "hibernating" PC, and the command screen came up, never fully connected but didn't get a response stating the port was closed. So I basically got a box with a fancy border on the outside until I killed the process on the remote (hibernating) PC.
do {}
While (get-process "XXXXXX.Win32" -ErrorAction SilentlyContinue | select -Property Responding)

$strTime = get-date
stop-process -force  -processname XXXXX.win32 
start-sleep -s 15
Invoke-Item "filelocation\XXXXX.Win32.exe"

Open in new window


 
0
 
Chris DentPowerShell DeveloperCommented:
Ouch, that's very difficult then.

It means the only way we can get a true picture is if we start interacting with the service on the other side. How easy that is depends on what the service is / does.

Is it a simple service? How would you normally use it? Alas simplicity in the service doesn't necessarily translate to simplicity on the network layer but no harm in looking :)

Chris
0
 
Dem-TechAuthor Commented:
To describe it, I would say it is "almost" like a telnet server. After the connection is made, it writes to a log file. The program "accepts" the connection from the user, then verifies the user name from our SQL server and grants access to the menu.

I was trying to use command prompt to execute a telnet session to it (with a .bat file) and think that could be successful if i can get it to return a true or false, 1 or 2 or 3. If it is working then I really don't need to know, I need to know when it is not working or hibernating. Using the telnet would almost work because after it connects to the remote machine the end user is given a log in screen.

 screenie.docx
0
 
Chris DentPowerShell DeveloperCommented:
Hmm we could try receiving data from the connection. It's something I've done before for testing SMTP connections.

This is where it gets a bit more complicated. I have a module which includes handlers for all of this kind thing, and from that, Test-Smtp would form our basic template.

http://www.indented.co.uk/index.php/2010/11/25/netshell/

All it does is receive then send ASCII encoded strings. It's entirely possible that we can get away with this modification to see if the service is responsive (assuming it posts a username / password prompt in ASCII on connection):
Function Test-Service {
  Param(
    [Parameter(Mandatory = $True)]
    [Net.IPAddress]$IPAddress,
    
    [UInt32]$Port = 23
  )

  $Socket = New-Socket -Protocol Tcp
  Receive-Bytes $Socket -IPAddress $IPAddress -Port $Port -ExpectPackets 1 `
    -ListenTimeout (New-TimeSpan -Seconds 30) | ConvertTo-String
  Remove-Socket $Socket
}

Import-Module NetShell
Test-Service 1.2.3.4

Open in new window

As the tail end of the code suggests, you need to have the module installed and loaded. It creates the underlying socket (New-Socket) and copes with receiving data (Receive-Bytes and ConvertTo-String).

Chris
0
 
Dem-TechAuthor Commented:
It retrieved output, which if the port is not responding it will not. So now the waiting game begins...
Below it what was returned.

==============================
                             
                             
                             
                             
   +[Login]==============+    
   |Barcode Gateway      |    
   |9.4.67.(?)           |    
   |User:*                |    
   |Pass:                |    
   |                     |    
   +=====================+    
                             
                             
0
 
Chris DentPowerShell DeveloperCommented:
Okay good. Lets see what happens when it break again then :)

Chris
0
 
Dem-TechAuthor Commented:
Well I made it through the night without an hiccups that my current script didn't catch. So the waiting game begins for today. Once I get some results I will let you know.

Thank you for all of your help so far.

Chris
0
 
Chris DentPowerShell DeveloperCommented:
This question has been classified as abandoned and is closed as part of the Cleanup Program. See the recommendation for more details.
0

Featured Post

Who's Defending Your Organization from Threats?

Protecting against advanced threats requires an IT dream team – a well-oiled machine of people and solutions working together to defend your organization. Download our resource kit today to learn more about the tools you need to build you IT Dream Team!

  • 7
  • 6
Tackle projects and never again get stuck behind a technical roadblock.
Join Now