Aunque la utilidad telnet ha caído en desgracia y prácticamente no tiene uso, se suele utilizar como una forma rápida de verificar la disponibilidad de un servidor y/o servicio remotos.
Automatizaremos en este uso a telnet, de forma que podamos usarlo en un script Bash.
$ # Si no dispones de un servidor telnet local...
$ telnet localhost
Trying ::1...
Trying 127.0.0.1...
telnet: Unable to connect to remote host: Connection refused
$
$ # Suponiendo que dispones de un servidor web local...
$ telnet localhost 80
Trying ::1...
Connected to localhost.
Escape character is '^]'.Qué pasaría si se incluyese al comando telnet en una pipe,
$ telnet localhost | echo 'pipe end'
pipe end
telnet: Unable to connect to remote host: Connection refused
$
$ telnet localhost 80 | echo 'pipe end'
pipe end
$$ telnet localhost | :
telnet: Unable to connect to remote host: Connection refused
$
$ telnet localhost 80 | :
$## # telnet_scan [server] [port] [timeout] # Try to connect at server:port with timeout # Defaults, # server, localhost # port, telnet port (23) # timeout, 3" # Returns, # 0, connection made # port open # 1, connection refused # network error or port closed # 129, timeout # port filtered or server error # # (c) 2017, xae. Juan José Eraso Escalona # 20170516 ## function telnet_scan {local server=${1:-localhost}
local port=${2:-23}
local timeout=${3:-3}
local resultresult=$(
(telnet "$server" "$port" | : )
2> >( read -t $timeout status;
[ $? -gt 128 ] &&
{ printf "timeout"; killall telnet; exit; };
[ -z "$status" ] && printf "open"
|| printf "closed"
))case $result in
open) return 0 ;;
timeout) return 129 ;;
*) return 1
esac}
A modo de ejemplo,
# Acepta pares servidor puerto # Finaliza al final de fichero o con entrada nulawhile read server port
do[ -z "$server" ] ||
[ -z "$port" ] && break;printf "$server:$port\t"
telnet_scan "$server" "$port"
case $? in
0) printf "abierto\n" ;;
1) printf "cerrado\n" ;;
*) printf "filtrado\n"
esacdone