gpt4 book ai didi

python - 在 bash 中调用一个 python 进程,然后将输出捕获到一个变量中

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:34:30 25 4
gpt4 key购买 nike

<分区>

我已经广泛搜索了这个答案,但它似乎仍然让我望而却步。我正在尝试编写一个 bash 脚本,该脚本将检查具有 ip:port 的多个服务器是否处于事件状态。由于 ping 不支持不同的端口(AFAIK),我找到了一个可以集成到 bash 中的漂亮的 python 1 衬里:

portping() { python <<<"import socket; socket.setdefaulttimeout(1); socket.socket().connect(('$1', $2))" 2> /dev/null && echo OPEN || echo CLOSED; }

这创建了一个可以从 bash 脚本中调用的函数移植,然后我想在包含主机列表的 txt 文件上使用它:

Contents of hosts.txt
myserver.host.com 3301
myserver.host.com 3302

然后我希望 bash 脚本从 hosts.txt 中读取两个变量 $ip 和 $port,移植这些变量,然后将“OPEN”或“CLOSED”的回显结果存储到一个变量中以供进一步操作(发送一个pushbullet 消息告诉我服务器已关闭)。

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}

但是我得到的输出是这样的:

$ ./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!

谎言!它没有生命:)显然问题出在 status = 行上。必须有一个简单的解决方法,但我太笨了,想不通!

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com