目录:
- 使用bash和
timeout
- 使用
nc
- 命令
- RHEL 6(nc-1.84)
- RHEL 7(nmap-ncat-6.40)
- 备注
使用bash和timeout
:
请注意,它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
使用nc
:
请注意,nc
RHEL 7上安装了向后不兼容的版本。
命令:
请注意,以下命令是唯一的,因为它对于RHEL 6和7是相同的。只是安装和输出是不同的。
$ nc -w $TIMEOUT_SECONDS -v $HOST $PORT </dev/null; echo $?
RHEL 6(nc-1.84):
安装:
$ sudo yum install nc
例子:
成功:
$ nc -w 2 -v canyouseeme.org 80 </dev/null; echo $?
Connection to canyouseeme.org 80 port [tcp/http] succeeded!
0
失败:
$ 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
例子:
成功:
$ 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
失败:
$ 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
)的参数和echo $?
命令当然仅用于说明。