在Shell脚本中使用telnet


8

我使用telnet命令检查MySQL端口是否正在响应。

telnet 10.10.10.24 3306

我使用ctrl字符断开连接。这按预期工作。如何在Shell脚本中使用此命令?


实际上,按照Janne的建议用换行符进行回显,并使用-w添加合理的超时值。
2011年

Answers:


12

如果您只是想检查端口是否打开,请尝试:

$ 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

谢谢。但是-z开关在服务器上运行,但在另一台服务器上不运行。我需要检查nc命令的版本吗?
shantanuo 2011年

也许。什么版本不起作用?
Cakemox

-z开关正常工作。我错了,请忽略以上评论。
shantanuo 2011年


4

如果您没有nc,则可以使用bash特殊文件重定向:

head -1 < /dev/tcp/10.10.10.24/3306 >/dev/null && echo MySQL is on || echo MySQL is off

2

要自动执行telnet脚本,应使用Expect。请参阅期望主页



0

我将使用netcat,而使用的是-w。

主机:〜user $ nc -w 1 1.2.6.1 3306
?
5.1.57-1〜dotdeb.1?WO`rA * L#h?b4z.pmT; i〜^; host:〜user $ 

0

这是在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 "'^]'."
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.