6

I'm trying to execute telnet command and getting the out put on shell script. But when the port not open or the ip not exist. The command take too much time to give the response. Will it be possible to limit the maximum try time on telnet?

telnet host port
  • What OS/distribution and which version of telnet (there are many variants in the world) are you using? Are you allowed to use other programs than telnet, for example netcat? – yaegashi Aug 21 '15 at 10:04
  • Oracle enterprise linux. And this is for some big company. They won't easily allow to install new tools. Need to use some thing in the server already. – sugunan Aug 21 '15 at 10:06
  • Related and maybe useful: stackoverflow.com/q/1128011/4937930 – yaegashi Aug 21 '15 at 10:24
  • nc not available in the server and they wont allow to install it also. – sugunan Aug 21 '15 at 10:29
  • 1
    nmap available on server ? Or just write a simple perl script, e.g. perlmonks.org/?node_id=571066 – steve Aug 21 '15 at 10:37
8

This will run for no more than 2 secounds:

[]# echo quit | timeout --signal=9 2 telnet [SERVER] [PORT]
3

Do you necessary have to run telnet? I think timeout(1) will help you.

Alternative #1: Use timeout, which is part of GNU coreutils. This won't confirm if you were able to establish a connection or not.

TIMEOUT=10 timeout $TIMEOUT telnet <host> <port>

Alternative #2: Use Bash/Perl/Python to solve the same problem, with more or less granularity.

A few examples:

Bash: TIMEOUT=10; telnet <host> <port> 2>&1 >/dev/null & WPID=$!; sleep $TIMEOUT && kill $! & KPID=$!; wait $WPID

Perl: perl -e "alarm 10; exec @ARGV" "telnet my.server.com 23"

Python: python -c 'import telnetlib;HOST="my.server.com"; PORT=23; TIMEOUT=10; PATTERN="Login: "; t = telnetlib.Telnet (HOST, PORT); t_read = t.read_until(PATTERN, TIMEOUT); print(repr(t_read))'

2

If scripting, you can run the telnet in background, and then if it's still running after a delay you can kill it. Example:

{ printf "HEAD /\n\n"; sleep 1; } | telnet hostname port & sleep 2 && kill %1 2>/dev/null && echo "timeout"

This waits 2 seconds before killing the backgrounded telnet.

1

You can consider the neater command netcat aka nc as discussed here

echo 'QUIT' | nc -w SECONDS YOUR_HOST PORT; echo $?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.