[树莓派网络监测]网络恢复自动发送邮件

作者: 管理员 分类: 设备趣玩 发布时间: 2021-07-02 19:44

看到QQ群里面有人在发这个,闲着无事,就写了一个脚本监控网络连通情况,这个脚本很简单,就是不停的去请求互联网,取URL返回的状态码,如果取不到代表网络中断,取到了代表网络连通,如果有中断即发邮件通知用户,具体脚本内容如下,脚本下载或者保存到本地请使用命令授权:chmod +x ip-mail.sh

#!/bin/bash
########################################
#    data:2021年7月2日                 #
#    blog:https://blog.hlhasd.com/     #
#                                      #
#######################################
# 后台启动方法 nohup /home/pi/xhsell/ip-mail.sh >/dev/null 2>&1 &
mail_log='/var/log/ip_mail.log'
mail_user='1327840813@qq.com' #发件人邮箱
mail_pass='#########'  #发件人密码,请使用在QQ获取的授权码
mail_addr='1327840813@qq.com' #收件人邮箱
fail=0
function mail_info(){
  eth0=`ifconfig eth0 | sed -n "2,2p" | awk '{print substr($2,1)}'`  
  wlan0=`ifconfig wlan0 | sed -n "2,2p" | awk '{print substr($2,1)}'`
  Public=`curl -s cip.cccurl cip.cc |grep -oP "\K([0-9]{1,3}[.]){3}[0-9]{1,3}" |awk 'NR==1'`
  str="检测到网络发生变化,新的网络信息如下:
eth0:$eth0
wlan0:$wlan0
公网地址:$Public" info=`sendemail -f $mail_user -t $mail_addr -s smtp.qq.com -u '网络发生变化通知' -o message-content-type=html -o message-charset=utf8 -xu $mail_user -xp $mail_pass -m $str` echo $info>>$mail_log } while true do text_time=$(date "+%Y-%m-%d %H:%M:%S") RET_CODE=`curl -I -s --connect-timeout 2 www.baidu.com -w %{http_code} | tail -n1` if [ "x$RET_CODE" = "x200" ]; then if [ $fail -ne 0 ];then echo $text_time " 网络已恢复,发送邮件...">>$mail_log mail_info fi sleep 20s fail=0 echo $fail else sleep 3s let fail++ if [ $fail -eq 1 ];then echo $text_time " 网络中断,等待恢复中..." >> $mail_log fi echo $fail fi done

附文件:

脚本下载

注意;请确保你的树莓派安装了sendemail,如果没有安装请使用下面命令进行安装:

apt-get install sendemail -y

最后就是这个脚本的开机自启动了,请编辑树莓派/etc/rc.local文件,在exit 0前面一行添加nohup /home/pi/xhsell/curl_monitor.sh >/dev/null 2>&1 &,脚本路径请换成自己的就可以了。

效果图:


发表评论

电子邮件地址不会被公开。