【问题标题】:How to send Internet connectivity alerts using a Bash script?如何使用 Bash 脚本发送 Internet 连接警报?
【发布时间】:2015-09-17 01:22:13
【问题描述】:

我的互联网连接不稳定,所以我决定制作一个 bash 脚本,它会在互联网恢复时提醒我。这是脚本:

#!/bin/bash
# set -x


while [ 1 ];do
  STATUS_CURRENT=$(ping -q -w 1 -c 1 google.com > /dev/null && echo connected || echo disconnected)
  if [[ $STATUS_CURRENT == "connected"  &&  $STATUS_LAST != "connected" ]];then
        aplay /home/user/bin/online.wav
        notify-send "We've connected"

 elif [[ $STATUS_CURRENT == "disconnected"  &&  $STATUS_LAST == "connected"  ]];then
       aplay /home/user/bin/offline.wav
       notify-send "Disconnected now"
  fi

   STATUS_LAST=$STATUS_CURRENT
   sleep 2
done

我在/etc/rc.local 中添加了它,让它在启动时执行。这个脚本的问题是它有时会失败。即使有 Internet 连接,脚本也会发送通知说它已断开连接(紧随其后的是“已连接”消息)。

如何避免这个问题?这是否与ping 失败缓慢的事实有关?脚本如何改进?

【问题讨论】:

  • 您应该至少 ping 一次以上。如,增加-c
  • @arco444:谢谢,我之前确实尝试过,但这只会导致脚本根本无法运行。不过,我不确定这是为什么。
  • 您还需要增加 -w 值。无论如何,这可能是您问题的根源,当然您可能会偶尔收到需要> 1秒的回复。如果脚本收到其中的一个,它将感知到连接已关闭。

标签: linux bash shell monitoring ping


【解决方案1】:

使用“netcat”它对我来说非常稳定

#!/bin/bash

status=0

do_on=("/home/user/bin/online.wav"
       "We've connected")

do_off=("/home/user/bin/offline.wav"
        "Disconnected now")

while [ 1 ] ;do
    nc -zw 2 google.de 80
    ret="$?"

    if [ "$ret" = 0 -a "$status" = 0 ] ;then
        aplay ${do_on[0]}
        notify-send ${do_on[1]}
        status=1

    elif [ "$ret" -ne 0 -a "$status" = 1 ] ;then
        aplay ${do_off[0]}
        notify-send ${do_off[1]}
        status=0 ;fi

    sleep 2 ;done

您应该提前测试您的 DNS 服务器

干杯卡里姆

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多