TOC:
使用bash和timeout
命令
例子
使用数控
命令
RHEL 6 (nc-1.84)
安装
例子
RHEL 7 (nmap-ncat-6.40)
安装
例子
讲话
使用bash和timeout:
请注意,超时应该在RHEL 6+中出现,或者在GNU coreutils 8.22中也可以找到。在MacOS上,使用brew install coreutils安装它,并将其用作gtimeout。
命令:
$ timeout $TIMEOUT_SECONDS bash -c "</dev/tcp/${HOST}/${PORT}"; echo $?
如果参数化主机和端口,请确保像上面那样将它们指定为${host}和${port}。不要仅仅将它们指定为$HOST和$PORT,即不带大括号;在这种情况下行不通。
例子:
成功:
$ timeout 2 bash -c "</dev/tcp/canyouseeme.org/80"; echo $?
0
失败:
$ timeout 2 bash -c "</dev/tcp/canyouseeme.org/81"; echo $?
124
如果必须保留bash的退出状态,
$ timeout --preserve-status 2 bash -c "</dev/tcp/canyouseeme.org/81"; echo $?
143
使用数控:
注意,在RHEL 7上安装了向后不兼容的nc版本。
命令:
注意,下面的命令是唯一的,因为它对于RHEL 6和7都是相同的。只是安装和输出不同而已。
$ nc -w $TIMEOUT_SECONDS -v $HOST $PORT </dev/null; echo $?
RHEL 6 (nc-1.84):
安装:
$ sudo yum install nc
例子:
Success:
$ nc -w 2 -v canyouseeme.org 80 </dev/null; echo $?
Connection to canyouseeme.org 80 port [tcp/http] succeeded!
0
Failure:
$ nc -w 2 -v canyouseeme.org 81 </dev/null; echo $?
nc: connect to canyouseeme.org port 81 (tcp) timed out: Operation now in progress
1
如果主机名映射到多个ip,上述失败的命令将循环遍历多个或所有ip。例如:
$ nc -w 2 -v microsoft.com 81 </dev/null; echo $?
nc: connect to microsoft.com port 81 (tcp) timed out: Operation now in progress
nc: connect to microsoft.com port 81 (tcp) timed out: Operation now in progress
nc: connect to microsoft.com port 81 (tcp) timed out: Operation now in progress
nc: connect to microsoft.com port 81 (tcp) timed out: Operation now in progress
nc: connect to microsoft.com port 81 (tcp) timed out: Operation now in progress
1
RHEL 7 (nmap-ncat-6.40):
安装:
$ sudo yum install nmap-ncat
例子:
Success:
$ nc -w 2 -v canyouseeme.org 80 </dev/null; echo $?
Ncat: Version 6.40 ( http://nmap.org/ncat )
Ncat: Connected to 52.202.215.126:80.
Ncat: 0 bytes sent, 0 bytes received in 0.22 seconds.
0
Failure:
$ nc -w 2 -v canyouseeme.org 81 </dev/null; echo $?
Ncat: Version 6.40 ( http://nmap.org/ncat )
Ncat: Connection timed out.
1
如果主机名映射到多个ip,上述失败的命令将循环遍历多个或所有ip。例如:
$ nc -w 2 -v microsoft.com 81 </dev/null; echo $?
Ncat: Version 6.40 ( http://nmap.org/ncat )
Ncat: Connection to 104.43.195.251 failed: Connection timed out.
Ncat: Trying next address...
Ncat: Connection to 23.100.122.175 failed: Connection timed out.
Ncat: Trying next address...
Ncat: Connection to 23.96.52.53 failed: Connection timed out.
Ncat: Trying next address...
Ncat: Connection to 191.239.213.197 failed: Connection timed out.
Ncat: Trying next address...
Ncat: Connection timed out.
1
备注:
-v(——verbose)参数和回显$?命令当然只是为了说明。