原文:http://stackoverflow.com/questions/4922943/test-from-shell-script-if-remote-tcp-port-is-open

法一:使用nc

nc -z <host> <port>

使用nc -z +IP或域名+端口检查目标主机端口是否开启,返回0则表示开启,返回1则表示未开启。

当然,为了更快的检测目标端口的状态,可以使用-w参数指定超时时间。(下方示例设置的超时时间为5秒)

nc -z -v -w5 <host> <port>$ nc -v -z -w 5 stackoverflow.com 80; echo $?
Connection to stackoverflow.com 80 port [tcp/http] succeeded!
0$ nc -v -z -w 5 stackoverflow.com 81; echo $?
nc: connect to stackoverflow.com port 81 (tcp) timed out: Operation now in progress
1------------------------------------------
SERVER=gitlab.com
PORT=22
`nc -z -v -w5 $SERVER $PORT`
result1=$?#Do whatever you wantif [  "$result1" != 0 ]; thenecho  'port 22 is closed'
elseecho 'port 22 is open'
fi
------------------------------------------

法二:使用bash

以下需要使用到timeout命令,对于CentOS5.x,安装方法见下:
wget ftp://ftp.pbone.net/mirror/ftp5.gwdg.de/pub/opensuse/repositories/home:/crt0solutions:/extras/CentOS_CentOS-5/x86_64/timeout-8.4-20.3.crt0.x86_64.rpm
#curl ftp://ftp.pbone.net/mirror/ftp5.gwdg.de/pub/opensuse/repositories/home:/crt0solutions:/extras/CentOS_CentOS-5/x86_64/timeout-8.4-20.3.crt0.x86_64.rpm -vO
rpm -ivh timeout-8.4-20.3.crt0.x86_64.rpm# Connection successful:
$ timeout 1 bash -c 'cat < /dev/null > /dev/tcp/google.com/80'
$ echo $?
0# Connection failure prior to the timeout
$ timeout 1 bash -c 'cat < /dev/null > /dev/tcp/sfsfdfdff.com/80'
bash: sfsfdfdff.com: Name or service not known
bash: /dev/tcp/sfsfdfdff.com/80: Invalid argument
$ echo $?
1# Connection not established by the timeout
$ timeout 1 bash -c 'cat < /dev/null > /dev/tcp/google.com/81'
$ echo $?
124

在这里,timeout会运行其后的子命令,若在指定的超时时间还未完成的话,timeout会kill掉子命令对应的进程。在这种情况下,bash就是一个子命令,用"/dev/tcp"的特殊方式尝试与目标主机的指定端口建连。

  1. 如果bash可以指定的超时时间内与目标主机端口建连,cat会立即终止(由于其是从/dev/null中读取内容),bash命令接着也会执行完毕,最终返回一个0状态码。

  2. 若在超时时间范围内与目标主机端口建连失败,bash会退出并与timeout一起返回一个1的状态码

  3. 若过了超时时间后bash还是无法成功建连,timeout就会kill掉bash并返回一个124的状态码

法三:使用pseudo-device file(</dev/tcp/$SERVER/$PORT)

#!/usr/bin/env bash
SERVER=example.com
PORT=80
</dev/tcp/$SERVER/$PORT
if [ "$?" -ne 0 ]; thenecho "Connection to $SERVER on port $PORT failed"exit 1
elseecho "Connection to $SERVER on port $PORT succeeded"exit 0
fi

测试:

$ ./test.sh
Connection to example.com on port 80 succeeded

融合为一行(判断本机11211端口是否存活)

</dev/tcp/localhost/11211 && echo Port open. || echo Port closed.

法四:使用perl(未测试,暂时无法保证可用性)

perl -MIO::Socket::INET -e 'exit(! defined( IO::Socket::INET->new("172.17.42.1:3142")))'

法五:使用nmap

前提是保证你的机器安装有nmap

open=`nmap -p $PORT $SERVER | grep "$PORT" | grep open`
if [ -z "$open" ]; thenecho "Connection to $SERVER on port $PORT failed"exit 1
elseecho "Connection to $SERVER on port $PORT succeeded"exit 0
fi

法六:使用telnet

其在mac与linux系统中都可以较好地工作。

使用方法:

$ is_port_open.sh 80 google.com
OPEN$ is_port_open.sh 8080 google.com
CLOSED

脚本内容:

PORT=$1
HOST=$2
TIMEOUT_IN_SEC=${3:-1}
VALUE_IF_OPEN=${4:-"OPEN"}
VALUE_IF_CLOSED=${5:-"CLOSED"}function eztern()
{if [ "$1" == "$2" ]thenecho $3elseecho $4fi
}# cross platform timeout util to support mac mostly
# https://gist.github.com/jaytaylor/6527607
function eztimeout() { perl -e 'alarm shift; exec @ARGV' "$@"; }function testPort()
{OPTS=""# find out if port is open using telnet# by saving telnet output to temporary file# and looking for "Escape character" response# from telnetFILENAME="/tmp/__port_check_$(uuidgen)"RESULT=$(eztimeout $TIMEOUT_IN_SEC telnet $HOST $PORT &> $FILENAME; cat $FILENAME | tail -n1)rm -f $FILENAME;SUCCESS=$(eztern "$RESULT" "Escape character is '^]'." "$VALUE_IF_OPEN" "$VALUE_IF_CLOSED")echo "$SUCCESS"
}testPort

使用timeout重新改写脚本(安装方法见法二,用法同上)

#!/bin/bashPORT=$1
HOST=$2
TIMEOUT_IN_SEC=${3:-1}
VALUE_IF_OPEN=${4:-"OPEN"}
VALUE_IF_CLOSED=${5:-"CLOSED"}function eztern()
{if [[ $1 = "$2" ]]thenecho $3elseecho $4fi
}function eztimeout() { perl -e 'alarm shift; exec @ARGV' "$@"; }function testPort()
{# find out if port is open using telnet# by saving telnet output to temporary file# and looking for "Escape character" response# from telnetFILENAME="/tmp/__port_check_$(uuidgen)"RESULT=$(timeout $TIMEOUT_IN_SEC telnet $HOST $PORT &> $FILENAME; cat $FILENAME | tail -n1|awk '{print $1$2}')rm -f $FILENAME;SUCCESS=$(eztern "$RESULT" "Escapecharacter" "$VALUE_IF_OPEN" "$VALUE_IF_CLOSED")echo "$SUCCESS"
}testPort

法七:使用wget(译者注:经测试该方法并不可行)

当诸如curl、telnet、nv、nmap这些工具都无法使用时,你可以使用wget来判断端口状态。

if [[ $(wget -q -t 1 --spider --dns-timeout 3 --connect-timeout 10  host:port; echo $?) -eq 0 ]]; then echo "OK"; else echo "FAIL"; fi

转载于:https://blog.51cto.com/xoyabc/1836353

shell中判断远程主机的某个tcp端口是否存活相关推荐

  1. python判断linux中文件是否存在_linux shell 中判断文件、目录是否存在的方法

    本文主要介绍了linux shell 中判断文件.目录是否存在的方法,分享给大家 -e filename 如果 filename存在,则为真 -d filename 如果 filename为目录,则为 ...

  2. shell中判断一个参数是否为整型

    shell中判断一个参数是否为整型 判断参数是否为整型 #!/bin/bashfunction IntTest() {for argdo#算术运算符,当参数为整型数字时,执行失败(( $arg )) ...

  3. Shell中判断字符串是否为数字的6种方法

    Shell中判断字符串是否为数字的6种方法 #!/bin/bash # 方法1 a=1234;echo "$a"|[ -n "`sed -n '/^[0-9][0-9]* ...

  4. shell获取hive查询数据结果_在shell中判断hive查询记录数大小

    用途: 根据查询到结果数量来判断,是否需要再执行下个脚本. 1. 查询语句script.q脚本如下: select count(1) as count from test; 2. shell脚本如下: ...

  5. linux判断目录是否存在命令,linux shell 中判断文件、目录是否存在的方法

    本文主要介绍了linux shell 中判断文件.目录是否存在的方法,分享给大家 -e filename 如果 filename存在,则为真 -d filename 如果 filename为目录,则为 ...

  6. Shell中判断字符串是否为数字的6种方法分享

    本篇文章主要介绍了"shell 判断字符串是否为数字",主要涉及到shell 判断字符串是否为数字方面的内容,对于shell 判断字符串是否为数字感兴趣的同学可以参考一下. #!/ ...

  7. Shell中判断文件,目录是否存在

    一. 具体每个选项对应的判断内容: -e filename 如果 filename存在,则为真 -d filename 如果 filename为目录,则为真 -f filename 如果 filena ...

  8. Linux Shell中判断进程是否存在的代码

    1 利用pgrep 匹配名字 复制代码 代码如下: if test $( pgrep -f $1 | wc -l ) -eq 0 then echo "进程不存在" else ec ...

  9. shell中判断控制语句 if case

    条件判断 case语句 case 变量引用 case 变量引用 in PAT1) 分支1 :: PAT2) 分支2 :: ........... *) ###相当于else 就是其他的::esac结尾 ...

最新文章

  1. 系统linux/redhat6.5 zabbix 2.47监控nginx1.8.0 (下)
  2. hive-数据倾斜记录分享
  3. matlab对矩阵的单个元素修改,怎么修改矩阵中的某些元素 或者简单点说保留矩阵中的元素...
  4. Selenium自动化测试框架
  5. 洛谷——P1012 拼数
  6. 批量删除指定user和transaction type对应order的report
  7. 在layui中使用 jquery 触发select 的 change事件无效
  8. 6.4.1-6.4.2树、森林、二叉树的转换
  9. C语言解析日志,存储数据到伯克利DB
  10. 5去掉button按钮的点击样式_各种好看的小按钮合集,纯css编写,最近在学习时遇到的,记录成为笔记...
  11. electron实践(2)
  12. 如何卸载CrossOver里的软件 ?快来看看吧
  13. python列表常用方法_python 列表常用方法
  14. 等比数列求和(递归)
  15. PHP实现微信小程序免密支付,微信免密支付,微信小程序实现微信支付功能!!!...
  16. 图神经网络解释性问题综述
  17. 彼得德鲁克管理理念摘写
  18. 基础的数组/链表实现的队列
  19. C. Candy Store(数学)
  20. 插入摄像头时,系统右下角提示:无法识别的USB设备:跟这台计算机连接的一个USB设备运行不正常...

热门文章

  1. python编译成class_python class
  2. python安装器要删吗_Centos7中,教你在不删除2.7下,安装python3
  3. 怎么查看python文件的代码_python实现代码查看列举目录下的文件
  4. php接口三结构,grape动态PHP结构(三)——API接口
  5. 学java里面包括php_【学习java和PHP区别你知道多少】
  6. Spring框架学习笔记09:基于XML配置方式搭建SSM框架实现用户登录
  7. Python数据分析学习笔记:使用SciKit-Learn进行数据规范化
  8. Java案例:连接SQL Server数据库,显示学生表记录
  9. 比较标签 php,比较标签 · ThinkPHP5.0完全开发手册 · 看云
  10. bzoj3192 [JLOI2013]删除物品 树状数组