PDA

View Full Version : Check connection with timeout, script telnet web server in script


bsddaemon
December 6th, 2008, 10:17
Hi guys, Im having trouble finding the way to:

Check the connection if it has been established with timeout:

1. Create the connection
2. Check if it has been established
3. If yes, then do something
4. If no, for timeout = 5 seconds, exit with error code.

Netcat sounds like a perfect tools for this task:


nc -w 5 domain.com port


But the timeout switch takes no effect. I googled and many others reported the same symptom

Script to telnet web server

Please see the attachment, I cant post here, for some reasons the forum complained the code with the "bad request" error

A similar script I wrote before was working, but unfortunately I forgot to keep copy of it. This time, it doesnt work. I must have syntax errors somewhere.

DutchDaemon
December 6th, 2008, 16:23
You could try net/tcping from ports.

# tcping -t 5 www.google.com 80
www.google.com port 80 open.
# echo $?
0

# tcping -t 5 www.google.com 90
www.google.com port 90 user timeout.
# echo $?
2


Easy to use in scripts:

if ( tcping -q -t 5 www.google.com 80 ); then echo alive; else echo dead; fi
alive

if ( tcping -q -t 5 www.google.com 90 ); then echo alive; else echo dead; fi
dead


Don't use 80 as a check port when you're behind a proxy server ;)

bsddaemon
December 6th, 2008, 18:12
Thanks, but the script will be run in web server, so I cant install any 3rd party application.

DutchDaemon
December 6th, 2008, 18:27
When you say that the timeout switch has no effect, what do you mean? That you never get your prompt back unless you ^C? Try adding the -o switch. Oh, there's also the -z flag to consider.

bsddaemon
December 6th, 2008, 18:49
Hi DutchDaemon,

My web server running Linux, there is no -o switch for netcat

Let me elaborate a bit more in details. In my case, it takes about 2 seconds to establish a new connection (a deamon with listening port)

I run this command in background mode:


$ command to create new connection &


Then I run netcat. Instead of keeping trying to connect for 5 seconds, netcat quits immediately if it fails at the first attempt:


nc -zw 5 hostname port


Thats why I said the timeout feature takes no effect.

bsddaemon
December 7th, 2008, 14:03
I came up with this function:


repeatCMD () {
count="0"

$@
while [ $? -ne 0 ]; do
sleep 1
echo " ===> I try again..."
count="$(($count + 1))"
if [ $count -eq 5 ]; then
echo " ===> ERR: Max number of retry. Quitting..."
exit 127
fi
$@
done
}


Now I can run the command:


repeatCMD nc -zw 5 hostname port


It works (doesnt exactly do the same job as timeout, though)

But Im sure you guys have a more elegant solution. Seriously, 12 line of code for the timeout switch doesnt sound right.

And I havent recalled what I have done with the telnet script :S