英文:
bash script for run another script after 5 unreachable ping request to specific ip or website
问题
我需要一个脚本,在特定IP的ping连续5次未响应后运行另一个脚本。但如果一切正常,不执行任何操作。例如,目前我有一个脚本,从文本文件中获取IP地址或网站列表,并运行ping命令,如果列表中的IP或网站不可达,它会运行另一个发送电报消息的脚本。但这不是一个好主意,因为通常可能只有1个不可达的响应,但整个网站是正常的或IP是可达的。现在我需要一个脚本,只在连续5次不可达响应后运行电报消息发送脚本,而不是在1次不可达响应后运行。以下是我的脚本:
date
cat /home/user/list.txt | while read output
do
unreachable_count=0
for i in {1..5}
do
ping -c 1 "$output" > /dev/null
if [ $? -eq 0 ]; then
echo "node $output is up"
unreachable_count=0
else
echo "node $output is down" >> /home/user/siteDown.log
unreachable_count=$((unreachable_count + 1))
fi
done
if [ $unreachable_count -eq 5 ]; then
message="$(echo "node $output is consistently down")"
telegram-send "$message"
fi
done
Thanks to all, have a nice day.
希望对你有所帮助。
英文:
I need script to run another script after 5 consistently 'unreachable' response from ping to specific ip. But if everything okay do nothing. For example for now I have script running ping command by taking ip addresses from text file which has list of ip or websites. And this script run another telegram message sending script if the ip or website from list is unreachable. But it is not good idea because often there can be just 1 unreacable response but overall the website is working or ip is reachable. Now I need the script which runs telegram message sending script after consistently 5 unreachable response. Not after 1 unreachable response. Here's my script:
date
cat /home/user/list.txt | while read output
do
ping -c 1 "$output" > /dev/null
if [ $? -eq 0 ]; then
echo "node $output is up"
else
message="$(echo "node $output is down")"
echo "node $output is down" > /home/user/siteDown.log
telegram-send "$message"
fi
done
Thank to all, have a nice days.
答案1
得分: 1
请尝试这个:
#!/bin/sh
try_ping() {
i=0
while [ $((i+=1)) -le 5 ] ; do
ping -c 1 "${1}" > /dev/null \
&& return 0
sleep 0.5
done
return 1
}
date
while read -r output ; do
if try_ping "${output}" ; then
echo "node $output is up"
else
echo "node $output is down" >> /home/user/siteDown.log
telegram-send "node $output is down"
fi
done </home/user/list.txt
我在每次ping尝试后添加了0.5秒的延迟,但你可以根据需要进行调整。
<details>
<summary>英文:</summary>
Try this:
#!/bin/sh
try_ping() {
i=0
while [ $((i+=1)) -le 5 ] ; do
ping -c 1 "${1}" > /dev/null \
&& return 0
sleep 0.5
done
return 1
}
date
while read -r output ; do
if try_ping "${output}" ; then
echo "node $output is up"
else
echo "node $output is down" >> /home/user/siteDown.log
telegram-send "node $output is down"
fi
done </home/user/list.txt
I added a 0.5 second sleep after every ping attempt, but you can adjust that.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论