linux - Bash Ping 站点检查脚本。 (超时时间更长)

标签 linux bash ping

我目前正在使用 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

最佳答案

是的,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 时总是双引号。

关于linux - Bash Ping 站点检查脚本。 (超时时间更长),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24280054/

相关文章:

linux - 从一个目录执行 bash 脚本到另一个目录?

linux - 将固定宽度的文件从文本转换为 csv

linux - gnuplot pgn 输出而不生成图

c - 如何增加C中正在运行的程序的堆栈大小

linux - 适用于 Linux 和 Solaris 的通用 grep 方法

c# - 如何从 winform C# ping 数据库

linux - 管理每周备份

linux - 下面的windows批处理脚本在mac和linux下如何对应?

bash - 在 Bash 脚本中并行使用 Ping

javascript - Discord.js Ping 号码的问题