我使用telnet命令来检查MySQL端口是否响应。
telnet 10.10.10.24 3306
我使用ctrl字符来断开连接。 这是按预期工作。 我如何在shell脚本中使用这个命令?
如果你只是想检查端口是否打开,请尝试:
$ nc -zv 10.10.10.24 3306 Connection to localhost 3306 port [tcp/mysql] succeeded!
如果端口打开, nc将返回0,否则返回1。 这对于脚本也是非常有用的。 省略v开关保持安静:
if ! nc -z 10.10.10.24 3306 then do_something fi
对于非交互式使用来说, nc要好得多。 尝试类似
echo -e "\n\n" | nc 10.10.10.24 3306
如果你没有nc,你可以使用bash特殊文件redirectons:
head -1 < /dev/tcp/10.10.10.24/3306 >/dev/null && echo MySQL is on || echo MySQL is off
要自动化telnet脚本,你应该使用expect。 看到期望的主页 。
这是我的任何具体情况的脚本。
host=localhost DATE=`date +%Y-%m-%d` TIME=`date +%H%M%S` LOG_OK=/tmp/telnet_ok LOG_FAIL=/tmp/telnet_falha for port in 80 25 22 443 110 do if telnet -c $host $port </dev/null 2>&1 | grep -q Escape; then echo "$DATE $TIME $port: Connected" >> $LOG_OK else echo "$DATE $TIME $port : no connection" >> $LOG_FAIL fi done
http://fajlinux.com.br/2014/10/10/script-monitorando-via-telnet/
我会使用netcat,而不是'-w';
主机:〜用户$ nc -w 1 1.2.6.1 3306 ? 5.1.57-1〜dotdeb.1?WO'rA * L#h?b4z.pmT; i〜^; host:〜user $
这里是如何在bash shell / expect中使用telnet
#!/usr/bin/expect # just do a chmod 755 one the script # ./YOUR_SCRIPT_NAME.sh $YOUHOST $PORT # if you get "Escape character is '^]'" as the output it means got connected otherwise it has failed set ip [lindex $argv 0] set port [lindex $argv 1] set timeout 5 spawn telnet $ip $port expect "'^]'."