测试远程 TCP 端口是否从 shell 脚本打开 [英] Test if remote TCP port is open from a shell script

查看:53
本文介绍了测试远程 TCP 端口是否从 shell 脚本打开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种快速而简单的方法,以便从 Shell 脚本内部正确测试给定的 TCP 端口是否在远程服务器上打开.

I'm looking for a quick and simple method for properly testing if a given TCP port is open on a remote server, from inside a Shell script.

我已经设法用 telnet 命令完成了它,当端口打开时它工作正常,但它似乎没有超时并且只是挂在那里......

I've managed to do it with the telnet command, and it works fine when the port is opened, but it doesn't seem to timeout when it's not and just hangs there...

这是一个示例:

l_TELNET=`echo "quit" | telnet $SERVER $PORT | grep "Escape character is"`
if [ "$?" -ne 0 ]; then
  echo "Connection to $SERVER on port $PORT failed"
  exit 1
else
  echo "Connection to $SERVER on port $PORT succeeded"
  exit 0
fi

我要么需要更好的方法,要么需要一种强制 telnet 超时的方法,例如,如果它在 8 秒内未连接,并返回一些我可以在 Shell 中捕获的内容(返回代码或标准输出中的字符串).

I either need a better way, or a way to force telnet to timeout if it doesn't connect in under 8 seconds for example, and return something I can catch in Shell (return code, or string in stdout).

我知道 Perl 方法,它使用 IO::Socket::INET 模块并编写了一个成功的脚本来测试端口,但希望尽可能避免使用 Perl.

I know of the Perl method, which uses the IO::Socket::INET module and wrote a successful script that tests a port, but would rather like to avoid using Perl if possible.

注意:这是我的服务器正在运行的地方(我需要从中运行它)

Note: This is what my server is running (where I need to run this from)

SunOS 5.10 Generic_139556-08 i86pc i386 i86pc

SunOS 5.10 Generic_139556-08 i86pc i386 i86pc

推荐答案

正如 B. Rhodes 所指出的,nc (netcat) 将完成这项工作.一种更紧凑的使用方式:

As pointed by B. Rhodes, nc (netcat) will do the job. A more compact way to use it:

nc -z <host> <port>

这样 nc 只会检查端口是否打开,成功时以 0 退出,失败时以 1 退出.

That way nc will only check if the port is open, exiting with 0 on success, 1 on failure.

进行快速交互式检查(超时 5 秒):

For a quick interactive check (with a 5 seconds timeout):

nc -z -v -w5 <host> <port>

这篇关于测试远程 TCP 端口是否从 shell 脚本打开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆