我有一個 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