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

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

问题描述

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

我已经设法使用telnet命令来完成此操作,并且在打开端口时它可以正常工作,但是在未打开端口时似乎并没有超时,而只是挂在那儿了...

这里是一个示例:

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秒的时间内没有连接,则强制telnet超时,然后返回我可以在Shell中捕获的内容(返回代码或stdout中的字符串). /p>

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

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

SunOS 5.10 Generic_139556-08 i86pc i386 i86pc

解决方案

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

nc -z <host> <port>

这样,nc将仅检查端口是否打开,成功则退出0,失败时退出1.

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

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

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.

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...

Here's a sample:

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

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).

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

解决方案

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

nc -z <host> <port>

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

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

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

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

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