<p>我已经广泛地寻找这个答案,但它似乎仍然没有找到我。
我正在尝试编写一个bash脚本,该脚本将检查多个具有ip:port的服务器是否处于活动状态。
由于ping不支持不同的端口(AFAIK),我找到了一个可以集成到bash中的漂亮的python 1行程序:</p>
<pre><code>portping() { python <<<"import socket; socket.setdefaulttimeout(1); socket.socket().connect(('$1', $2))" 2> /dev/null && echo OPEN || echo CLOSED; }
</code></pre>
<p>这将创建一个可以在bash脚本中调用的函数portping,然后我想在包含主机列表的txt文件中使用它:</p>
<pre><code>Contents of hosts.txt
myserver.host.com 3301
myserver.host.com 3302
</code></pre>
<p>然后我想让bash脚本从主机.txt两个变量$ip和$port,对这些变量进行portping,然后将“OPEN”或“CLOSED”的回显结果存储到一个变量中以供进一步操作(发送pushbullet消息告诉我服务器已关闭)。你知道吗</p>
<pre><code>while read ip port;
do
echo "Checking if $ip port $port is alive"
portping $ip $port # debug check to see if python function is actually working
status = 'portping $ip $port' # herein lies my issue, how do I get the python functions echo output into the variable ?
echo "$ip $port is $status"
if [ "$status" == "CLOSED" ]
then
echo "Sending pushbullet notification"
# pushbullet stuff;
else
echo "It's Alive!"
fi
done < ${HOSTS_FILE}
</code></pre>
<p>但是我得到的结果是:</p>
<pre><code>$ ./pingerWithPython.sh hosts.txt
Using file hosts.txt
Checking if myserver.host.com port 3301 is alive
OPEN
status: Unknown job: =
myserver.host.com 3301 is
It's Alive!
Checking if myserver.host.com port 3302 is alive
CLOSED
status: Unknown job: =
myserver.host.com 3302 is
It's Alive!
</code></pre>
<p>谎言!它不是活着的:)
很明显,问题在于status=line。一定有一个简单的解决办法,但我太n00b想不出来!你知道吗</p>