Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

check connectivity of a port 1

Status
Not open for further replies.

ac325ci

MIS
Jan 16, 2004
128
US
im trying to write a script to check connectivity to a port.. what is the best way to achieve this ? if port is listening on target server then return code 0..thanks
 
Something like:

[tt]if telnet hostname portnumber < /dev/null 2>&1 | grep refused
then
return 1
else
return 0
fi[/tt]

Annihilannic.
 
Annihilannic, is there a way to allow this attempt for like 5 secs or so ? prob is when the machine is down , the script sits there waiting telnet hostname 22|grep refuse to finish.. takes a long time.. ie

+ telnet hostname 22
+ 0< /dev/null 2>& 1
+ grep refused


 
Maybe a simple ping would be faster? Maybe not...

Alan Bennett said:
I don't mind people who aren't what they seem. I just wish they'd make their mind up.
 
ping won't test whether a specific port is open, but it's a good idea nonetheless... i.e. first ping the host to see if it is up at all, and then attempt the telnet. You can usually set a short timeout on the ping to speed it up as well. If the host is up but the port is closed, then the telnet should fail to connect immediately.

Annihilannic.
 
yes, im pinging the host first before attemptin but the prob is that some servers are behind firewalls and icmp requests are turned off
 
You could try something like this with a background timer to kill the telnet after a short while:

Code:
#!/bin/ksh

# Hide the messages about terminated processes.
exec 2> /dev/null

function testport()
{
        (
                if sleep 10
                then
                        ps -o pid,comm | awk 'NR > 1 && /telnet/ {print $1}' | xargs -r kill
                fi
        ) &

        if telnet $1 $2 < /dev/null 2>&1 | grep -1 '^Connected'
        then
                RETURN=0
        else
                RETURN=1
        fi

        ps -o pid,comm | awk 'NR > 1 && /sleep/ {print $1}' | xargs -r kill

        return $RETURN
}

testport localhost 26 && echo localhost 26 is open || echo localhost 26 is closed
testport nothing 26 && echo nothing 26 is open || echo nothing 26 is closed
testport localhost 25 && echo localhost 25 is open || echo localhost 25 is closed
testport example.com 25 && echo example.com 25 is open || echo example.com 25 is closed

Annihilannic.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top