• This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn more.

Check connection with timeout, script telnet web server in script

bsddaemon

Active Member

Thanks: 14
Messages: 101

#1
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.
 

Attachments

DutchDaemon

Administrator
Staff member
Administrator
Moderator

Thanks: 2,462
Messages: 11,087

#2
You could try net/tcping from ports.

Code:
# tcping -t 5 www.google.com 80
www.google.com port 80 open.
# echo $?
0
Code:
# tcping -t 5 www.google.com 90
www.google.com port 90 user timeout.
# echo $?
2
Easy to use in scripts:

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

Active Member

Thanks: 14
Messages: 101

#3
Thanks, but the script will be run in web server, so I cant install any 3rd party application.
 

bsddaemon

Active Member

Thanks: 14
Messages: 101

#5
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

Active Member

Thanks: 14
Messages: 101

#6
I came up with this function:

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

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