在Openwrt中获取WAN口IP地址并推送至微信
在Openwrt中获取WAN口IP地址并推送至微信
前言
自从捡回了蜗牛用于家用NAS后,使用公网IP访问家里的服务更加频繁。虽然家里的软路由已经配置了DDNS来更新IP域名绑定信息,但偶尔还是出现了几次插件运行出错。于是自己写了一个获取WAN口IP并利用 Server酱 推送至微信的脚本,通过Crontab定时任务执行来检查IP是否变化。
2021/12/01 增加了推送到企业微信的版本分享出来。
代码部分
#/bin/ash
#用于openwrt
#updata 2020/12/19 23:07
#start
echo "==========开始=========="
echo `date '+%Y-%m-%d %H:%M:%S'`
#获取当前wan_ip
current_wan_ip=`ifconfig -a | grep inet | grep -v inet6 | grep -v 127.0.0.1 | grep -v 192.168.0.1 | awk '{print $2}' | tr -d "addr:"`
echo "IP: $current_wan_ip"
#是否存在ip.txt
if [ ! -f "/tmp/ip.txt" ]; then
echo "不存在ip.txt文件"
#第一次推送ip
content="?text=路由器IP已更新&""desp=当前IP:"$current_wan_ip
url="https://sc.ftqq.com/Server酱KEY已隐去.send"$content
curl $url
echo "已推送当前ip"
echo ${current_wan_ip} > /tmp/ip.txt
echo "当前IP已写入ip.txt"
else
last_ip=`cat /tmp/ip.txt`
if [ "${current_wan_ip}" != "${last_ip}" ]; then
#发送新ip并更新ip.txt
content="?text=路由器IP已更新&""desp=当前IP:"$current_wan_ip
url="https://sc.ftqq.com/Server酱KEY已隐去.send"$content
curl $url
echo ${current_wan_ip} > /tmp/ip.txt
echo "已推送新ip并更新ip.txt"
else
echo "IP无变化,不需要推送"
fi
fi
echo `date '+%Y-%m-%d %H:%M:%S'`
echo -e "==========结束==========\n"
#end
企业微信webhook版本
#/bin/ash
#用于openwrt
#updata 2021/03/31 更新为企业微信机器人推送通道
#start
echo "==========开始=========="
echo `date '+%Y-%m-%d %H:%M:%S'`
#企业微信机器人webhook
webhook="https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=自己的key"
#获取当前wan_ip
current_wan_ip=`ifconfig -a | grep inet | grep -v inet6 | grep -v 127.0.0.1 | grep -v 192.168.0.1 | grep -v 172.17.0.1 | awk '{print $2}' | tr -d "addr:"`
echo "IP: $current_wan_ip"
#是否存在ip.txt
if [ ! -f "/tmp/ip.txt" ]; then
echo "不存在ip.txt文件"
#第一次推送ip
content="路由器IP已更新\n当前IP: ""$current_wan_ip"
curl "$webhook" -H "Content-Type: application/json" -d "{\"msgtype\":\"text\",\"text\":{\"content\":\"$content\"}}"
echo "已推送当前ip"
echo ${current_wan_ip} > /tmp/ip.txt
echo "当前IP已写入ip.txt"
else
last_ip=`cat /tmp/ip.txt`
if [ "${current_wan_ip}" != "${last_ip}" ]; then
#发送新ip并更新ip.txt
content="路由器IP已更新\n当前IP: ""$current_wan_ip"
curl "$webhook" -H "Content-Type: application/json" -d "{\"msgtype\":\"text\",\"text\":{\"content\":\"$content\"}}"
echo "已推送当前ip"
echo ${current_wan_ip} > /tmp/ip.txt
echo "IP已更新至ip.txt"
else
echo "IP无变化,不需要推送"
fi
fi
echo `date '+%Y-%m-%d %H:%M:%S'`
echo -e "==========结束==========\n"
#end
部署
-
上传该脚本并赋予执行权限
chmod a+x check_ip.sh
-
编辑crontab任务计划
crontab -e
进入任务计划列表添加以下任务,每5分钟执行一次脚本,并将执行结果写入到push.log文件中:
*/5 * * * * /usr/bin/myscripts/check_ip/check_ip.sh >> /usr/bin/myscripts/check_ip/push.log 2>&1 &
-
通过push.log查看运行情况
root@OpenWrt:~# tail -f /usr/bin/myscripts/check_ip/push.log 2020-12-219 23:14:00 ==========开始========== 2020-12-19 23:15:00 IP: xx.xx.72.193 IP无变化,不需要推送 2020-12-19 23:15:00 ==========结束========== ==========开始========== 2020-12-19 23:20:00 IP: xx.xx.72.193 IP无变化,不需要推送 2021-02-19 23:20:00 ==========结束==========