Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Verify a program accepts a connection through Port

Posted on 2011-03-02
14
Medium Priority
?
943 Views
Last Modified: 2013-12-13
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
Comment
Question by:Dem-Tech
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 6
14 Comments
 
LVL 71

Expert Comment

by:Chris Dent
ID: 35025068

> 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
 

Author Comment

by:Dem-Tech
ID: 35026409
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
 
LVL 71

Expert Comment

by:Chris Dent
ID: 35026446
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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:Dem-Tech
ID: 35026578
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
 
LVL 71

Expert Comment

by:Chris Dent
ID: 35026600
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
 

Author Comment

by:Dem-Tech
ID: 35030281
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
 
LVL 71

Expert Comment

by:Chris Dent
ID: 35030530
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
 

Author Comment

by:Dem-Tech
ID: 35030677
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
 
LVL 71

Accepted Solution

by:
Chris Dent earned 2000 total points
ID: 35030816
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
 

Author Comment

by:Dem-Tech
ID: 35031012
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
 
LVL 71

Expert Comment

by:Chris Dent
ID: 35031047
Okay good. Lets see what happens when it break again then :)

Chris
0
 

Author Comment

by:Dem-Tech
ID: 35036239
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
 
LVL 71

Expert Comment

by:Chris Dent
ID: 35687971
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

Are your AD admin tools letting you down?

Managing Active Directory can get complicated.  Often, the native tools for managing AD are just not up to the task.  The largest Active Directory installations in the world have relied on one tool to manage their day-to-day administration tasks: Hyena. Start your trial today.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Recently we ran in to an issue while running some SQL jobs where we were trying to process the cubes.  We got an error saying failure stating 'NT SERVICE\SQLSERVERAGENT does not have access to Analysis Services. So this is a way to automate that wit…
One-stop solution for Exchange Administrators to address all MS Exchange Server issues, which is known by the name of Stellar Exchange Toolkit.
This video shows how use content aware, what it’s used for, and when to use it over other tools.
In this brief tutorial Pawel from AdRem Software explains how you can quickly find out which services are running on your network, or what are the IP addresses of servers responsible for each service. Software used is freeware NetCrunch Tools (https…

704 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question