在Mac OS X 10.10上使用netcat,我想测试Facilis TerraBlock服务器上每分钟的监听端口,以确认以太网监听器是否正常运行。
我希望脚本输出一行成功,一行输出失败,并在前一行记录日期/时间戳。我现在不需要将任何记录到文件中。
这些本地nectat输出之类的东西是理想的:
Wed Feb 4 10:49:09 EST 2015
Connection to 10.40.255.11 port 859 [tcp/*] succeeded!
nc: connectx to 10.40.255.12 port 859 (tcp) failed: Connection refused
这是我创建的脚本:
#!/bin/bash
date
nc -z 10.40.255.11 859 || nc -vz 10.40.255.11 859
nc -z 10.40.255.12 859 || nc -vz 10.40.255.12 859
while sleep 60; do date;nc -z 10.40.255.11 859 || nc -vz 10.40.255.11 859 & nc -z 10.40.255.12 859 || nc -vz 10.40.255.12 859; done
这个脚本行为不可预测,我推测它是||操作员,但我找不到另一种方法来做到这一点。具体来说,当脚本运行时,终端输出在时间戳之后的第一个或第二个.11和.12测试之间交替进行,这让我想知道它是否只是netcat响应的连接超时,导致回复偶尔会被删除订单,或者如果有更大的问题,我的脚本返回不可靠的数据。
以下是我当前输出的示例:
Fri Feb 6 10:51:33 EST 2015
Connection to 10.40.255.11 port 859 [tcp/*] succeeded!
Connection to 10.40.255.12 port 859 [tcp/*] succeeded!
Fri Feb 6 10:51:34 EST 2015
Connection to 10.40.255.12 port 859 [tcp/*] succeeded!
Connection to 10.40.255.11 port 859 [tcp/*] succeeded!
Fri Feb 6 10:51:35 EST 2015
Connection to 10.40.255.12 port 859 [tcp/*] succeeded!
Connection to 10.40.255.11 port 859 [tcp/*] succeeded!
Fri Feb 6 10:51:36 EST 2015
Connection to 10.40.255.11 port 859 [tcp/*] succeeded!
Connection to 10.40.255.12 port 859 [tcp/*] succeeded!
我添加了||和&运算符和看似冗余的代码,因为我只想在连接失败时看到netcat的详细输出。
答案 0 :(得分:0)
您的脚本可能更加可靠,如下所示:
#! /bin/bash
ips="10.40.255.11 10.40.255.11 10.40.255.12 10.40.255.12"
while true ; do
# This will make sure it will run every 60 seconds, not 60 seconds + whatever nc takes to execute
sleep 60 &
date
for ip in $ips; do
# Note that we're using -w to timeout
out=$(nc -zvw 2 $ip 859 2>&1) && echo "$out" && break
done || echo "$out"
# This waits for sleep in background
wait
done