添加路由器定时任务监控指定设备状态

Published: Tags: OPENWRT SHELL

新增脚本:自行修改路径,记得赋予执行权限

vi /koolshare/scripts/merlin_wxfirm_alert.sh

代码逻辑:自行修改以下注释的内容或者设定

#!/bin/sh

PIDOF=$(pidof "${0##*/}") && [ "$PIDOF" != "$$" ] && exit

macAddr='3j:k5:r9:4i:x7:6m' #小写MAC地址
NET_ARP(){ awk "/$macAddr/{print \$3; exit 1}" /proc/net/arp && echo 0x0; }

oldFlag=$(NET_ARP); while true; do newFlag=$(NET_ARP)

if [ "$oldFlag" != "$newFlag" ] && [ -n "$newFlag" ]; then
    robotId="K9BzZc6y-NVPl-04mY-vITn-AtQJL25XMjbD" #群机器人
    url="https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=$robotId"
    
    payload='{"msgtype":"text","text":{"content":"MESSAGE"}}'
    message="$(date +%Y/%m/%d-%H:%M:%S) 设备 $macAddr 信号 $newFlag"
    
    needWarn="YES"; [ "$newFlag" == "0x2" ] && message="$message 连接↑"
    if [ "$newFlag" == "0x0" ]; then cntNum=0; message="$message 断开↓"
        while [ $cntNum -le 99 ]; do cntNum=$(($cntNum+1)); A=`NET_ARP`
            [ -n "$A" ] && [ "$A" != "0x0" ] && needWarn="NO" && break
        sleep 6; done #延迟确认离开
    fi
    
    if [ "$needWarn" == "YES" ]; then oldFlag="$newFlag"
        curl -gsm 5 -d "${payload/MESSAGE/$message}" "$url" &> /dev/null
    fi
fi

URANDOM=$(< /dev/urandom tr -dc '123456789' |head -c 9)
[ $(($URANDOM%86400)) -eq 1 ] && exit; sleep 1; done #监控间隔

定时任务:crontab -e

* * * * * /koolshare/scripts/merlin_wxfirm_alert.sh &