我目前正在使用Raspberry PI作为 ping服务器,这是我用来检查ok响应的脚本。
我不熟悉bash脚本,所以这是一个关于curl调用的初学者问题,有没有办法增加超时,因为它一直报告虚假网站。
#!/bin/bash
SITESFILE=/sites.txt #list the sites you want to monitor in this file
EMAILS=" " #list of email addresses to receive alerts (comma separated)
while read site; do
if [ ! -z "${site}" ]; then
CURL=$(curl -s --head $site)
if echo $CURL | grep "200 OK" > /dev/null
then
echo "The HTTP server on ${site} is up!"
sleep 2
else
MESSAGE="This is an alert that your site ${site} has failed to respond 200 OK."
for EMAIL in $(echo $EMAILS | tr "," " "); do
SUBJECT="$site (http) Failed"
echo "$MESSAGE" | mail -s "$SUBJECT" $EMAIL
echo $SUBJECT
echo "Alert sent to $EMAIL"
done
fi
fi
done < $SITESFILE
答案 0 :(得分:1)
是的,man curl
:
--connect-timeout <seconds>
Maximum time in seconds that you allow the connection to the server to take.
This only limits the connection phase, once curl has connected this option is
of no more use. See also the -m, --max-time option.
在调用curl之前,您还可以考虑使用ping
来测试连接。带ping -c2
的东西会给你2个ping来测试连接。然后只检查ping的返回(即[[ $? -eq 0 ]]
表示ping成功,然后连接curl)
此外,您可以使用[ -n ${site} ]
(已设置网站)而不是[ ! -z ${site} ]
(网站未设置)。此外,您通常希望使用[[ ]]
测试关键字而不是单个[ ]
来构建测试结构。为了获得最终的可移植性,只需使用test -n "${site}"
(使用test
时始终使用双引号。
答案 1 :(得分:1)
我认为您需要此选项--max-time <seconds>
-m/--max-time <seconds>
Maximum time in seconds that you allow the whole operation to take. This is useful for preventing your batch jobs from hanging for hours
due to slow networks or links going down.
--connect-timeout <seconds>
Maximum time in seconds that you allow the connection to the server to take. This only limits the connection phase, once curl has connected this option is of no more use.