我有一个 bash 函数,它通过从文本文件中一一读取服务器的 IP 来检查服务器上是否有正在运行的进程
while read IP
do
if [ 1 -eq "$(echo "$(ssh -n ubuntu@$IP "top -b -n2 -d 0.5|grep Cpu|awk '{print \$2+\$4}'|tail -n1") > 1.0" | bc)" ];then
echo "process is running on $IP"
else
echo "process is not running on $IP"
fi
done < file.ips
file.ips 包含很少的服务器 ip
202.X.X.X
203.X.X.X
204.X.X.X
...
...
...
我想修改这个函数来检查并行运行在多个服务器上的进程
答案1
使用 GNU Parallel,您可以执行以下操作:
check() {
IP="$1"
if [ 1 -eq "$(echo "$(ssh -n ubuntu@$IP "top -b -n2 -d 0.5|grep Cpu|awk '{print \$2+\$4}'|tail -n1") > 1.0" | bc)" ];then
echo "process is running on $IP"
else
echo "process is not running on $IP"
fi
}
export -f check
parallel -j0 check < file.ips
答案2
在后台运行循环的内容怎么样?
while read IP
do
(if [ 1 -eq "$(echo "$(ssh -n ubuntu@$IP "top -b -n2 -d 0.5|grep Cpu|awk '{print \$2+\$4}'|tail -n1") > 1.0" | bc)" ];then
echo "process is running on $IP"
else
echo "process is not running on $IP"
fi) &
done < file.ips