定时获取公网ip并发送邮件提醒

前一段时间路由器刷的老毛子固件“穿透服务”中定时更新阿里DDNS失败了,用了很久第一次遇到。所以需要做个备用的措施用来实时获取公网ip信息

1、基于python实现

  • 开启邮箱的SMTP功能
  • 拿到授权码(不是登录密码)
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
import re
import random
import requests
import logging
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from string import Template
from email.utils import parseaddr, formataddr
# 输出日志格式
logging.basicConfig(format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s',level=logging.INFO,filename='sendWANIP.log',filemode='a')def _format_addr(s):"""美化邮箱地址,用于可显示发/收件人:param s: 邮件地址:return: 美化后的地址"""addr = parseaddr(s)return formataddr(addr)def get_current_ip():"""获取当前公网ip地址:return: 公网ip地址"""ip_reg = re.compile("((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})(\\.((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})){3}")# 可根据需求增删获取ip网址api_tuple = ("http://txt.go.sohu.com/ip/soip","https://ident.me/","https://ifconfig.me/ip","https://icanhazip.com/","https://checkip.amazonaws.com/","http://members.3322.org/dyndns/getip")url = api_tuple[random.randrange(len(api_tuple))]# print(url)r = requests.get(url)ip = re.findall(r'\d+.\d+.\d+.\d+', r.text)# ip[0]if re.match(ip_reg,ip[0]):logging.info("从{}获取地址成功!ip={}".format(url,ip))return ip[0]else:logging.error("从{}获取地址失败!".format(url))exit(-1)def record_ip(params):"""将最新的ip记录在文件中:param params: 包含ip的参数"""filename="./lastwanip"last_wan_ip=""if os.path.exists(filename):f=open(filename,'r');last_wan_ip=f.readline()f.close()logging.info("从文件中读到ip地址为:{}".format(last_wan_ip))if last_wan_ip!= params['current_ip']:f = open(filename, 'w');f.write(params['current_ip'])f.close()else:logging.info("ip地址已经是最新的,无需更新")exit(0)
def send_mail(params):"""给指定用户发送邮件:param params: 发送邮件信息:return: 0: 发送成功,>0 发送失败"""# 第三方 SMTP 服务mail_host = "smtp.163.com"  # 设置服务器mail_user = "xxxx"  # 用户名mail_pass = "xxxxxxxx"  # 口令,即授权码不是账户密码receivers = sender = 'xxxx@163.com'# 邮件内容支持html格式,仿照的腾讯云模板mail_text="""<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>IP地址</title></head><body><div><includetail><div align="center"><div class="open_email" style="margin-left: 8px; margin-top: 8px; margin-bottom: 8px; margin-right: 8px;"><div><br><span class="genEmailContent"><div id="cTMail-Wrap"style="word-break: break-all;box-sizing:border-box;text-align:center;min-width:320px; max-width:660px; border:1px solid #f6f6f6; background-color:#f7f8fa; margin:auto; padding:20px 0 30px; font-family:'helvetica neue',PingFangSC-Light,arial,'hiragino sans gb','microsoft yahei ui','microsoft yahei',simsun,sans-serif"><div class="main-content" style=""><table style="width:100%;font-weight:300;margin-bottom:10px;border-collapse:collapse"><tbody><tr style="font-weight:300"><td style="width:3%;max-width:30px;"></td><td style="max-width:600px;"><div id="cTMail-logo" style="width:92px; height:25px;"><a href="#"><img id="logo" border="0" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAALcAAABCCAYAAAAVMUc1AAAAAXNSR0IB2cksfwAAAAlwSFlzAAAOxAAADsQBlSsOGwAAGVNJREFUeJztXQl4FFW2xvW9N8ubUZCdhDWrISskgWxkJSSBIMqissiAGgFRcVBxVNQZHRdkGH3AoAaSEAiIbCK4gbiyGpAtEEBZxBi2AOm9uuqfe25Vdao73enOgnGe9ee7X3W6qm7frvrvuf8959TtNm106NChQ4cOHTp06NChQ4cOHTp06NChQ4cOHW3+9PAstA+OQ4e+KQhKGoE7pszGnx5/Be/vPLpbexwk3NBabdSho0nIGj0R85ZtwvS/LUL62BnoETsUfwxIxM2hg9AlIg3ZoyZhQWEZICKgtduqQ0ejMGZiAQ6crIYZQK0EWNi22iThn0vXY9zDs3Fzzyh0DojBG4uWYf0HXwp7jlaHNaZ+O3SLr6OVMGPWc9h39AQERmqj1QJGRk7wK6xcZOV79uKL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xi14ce6/MOuvr2H8lMdw/8zn0S2M1voeyH8ir3N4OiIy70J09gTcNuVZjCiYjZ7xOYzkSejSNxGJw8biL3MWYNfhk/I6JzY4fkHBorgULcryw1RsisWuscDxGzof7ziELkHx6B0+SLfYOnzDc3MXYvS9D8M/LA5+oTHwY0TvHhQNv1vjOYF7x6Sha3A8OgX0Z8cMQMeAaHQKjEFMSi4G3z4Bj85+FUdO1fgz0gaw0lZb9wdflf+YP/ZedOgTweqLRe+oREye8TR2Hj7N1zpR1wBXA0lGZWQw2OtGieM/nceg3NvQqU8k+vRNRsFDz+nk1uE7GLmuul+YkfcaVjJffONtdO8bjx7hCaBfSaO0VOpAQ8dNw+j7H0P+hOnyrwwHR6NnaBSSsnJRsmqdTmgdv2wwg3wD09J3MklSvnrjVkydORsDs0eiT/9MtGWSo11IMjpHZ+OWkERk3T4Waz/cQha9JROfdOi4emAyuwcjeY7gImEIa7buRcnGbdj3w5Xu9D/rBDf+7A3UoaM5sLdcfrUOHTp06NChQ4cOHTp06NChQ4cOHT8jaB0UVlr0N4V06GhVMEJfz0oHVoazko5f0NNN/wYV+1KRa3imowAAAABJRU5ErkJggg=="style="width:183px; height:66px;display:block"></a></div><br/><p style="height:2px;background-color: #00a4ff;border: 0;font-size:0;padding:0;width:100%;margin-top:20px;"></p><div id="cTMail-inner" style="background-color:#fff; padding:23px 0 20px;box-shadow: 0px 1px 1px 0px rgba(122, 55, 55, 0.2);text-align:left;"><table style="width:100%;font-weight:300;margin-bottom:10px;border-collapse:collapse;text-align:left;"><tbody><tr style="font-weight:300"><td style="width:3.2%;max-width:30px;"></td><td style="max-width:480px;text-align:left;"><h1 id="cTMail-title" style="font-size: 20px; line-height: 36px; margin: 0px 0px 22px;">[DynamicIP-Notice]</h1><p id="cTMail-userName" style="font-size:14px;color:#333; line-height:24px; margin:0;"><span>Your current public ip address is :<strong>${current_ip}</strong>.</span></p><dl style="font-size: 14px; color: rgb(51, 51, 51); line-height: 18px;"><dd style="margin: 0px 0px 6px; padding: 0px; font-size: 12px; line-height: 22px;"><p id="cTMail-sender" style="font-size: 14px; line-height: 26px; word-wrap: break-word; word-break: break-all; margin-top: 32px;">Sincerely,<br><strong>${device}</strong></p></dd></dl></td><td style="width:3.2%;max-width:30px;"></td></tr></tbody></table></div><div id="cTMail-copy" style="text-align:center; font-size:12px; line-height:18px; color:#999"><table style="width:100%;font-weight:300;margin-bottom:10px;border-collapse:collapse"><tbody><tr style="font-weight:300"><td style="width:3.2%;max-width:30px;"></td><td style="max-width:540px;"><p style="text-align:center; margin:20px auto 14px auto;font-size:12px;color:#999;">如非本人邮件,请忽略!</p><td style="width:3.2%;max-width:30px;"></td></tr></tbody></table></div></td><td style="width:3%;max-width:30px;"></td></tr></tbody></table></div></div></span></div></div></div></includetail></div></body></html>"""mail = MIMEText(Template(mail_text).substitute(params), 'html', 'utf-8')# 显示发件人mail['From'] = _format_addr(sender)mail['To'] = _format_addr(receivers)# 设置邮件主题subject = '[DynamicIP-Notice] {}'.format(params['current_ip'])mail['Subject'] = Header(subject, 'utf-8')try:smtpObj = smtplib.SMTP()smtpObj.connect(mail_host, 25)  # 25 为 SMTP 端口号smtpObj.login(mail_user, mail_pass)smtpObj.sendmail(sender, receivers, mail.as_string())logging.info("邮件发送成功,最新ip为{}".format(params['current_ip']))return 0except smtplib.SMTPException as ex:logging.error("邮件发送失败{},".format(ex))return 1if __name__=='__main__':device = os.environ['COMPUTERNAME']params = {"current_ip": get_current_ip(), "device": device}record_ip(params)send_mail(params)

2、创建bat文件启动脚本

"D:\Program Files\Python310\python.exe" D:\Code\Code\sendWANIP\sendWANIP.py

3、Windows任务计划

添加windows任务计划,每隔10分钟执行bat文件获取公网ip
注意:

  • “程序或脚本”中写的可执行文件不要被引号包裹
  • 起始位置必填,为可执行文件所在的目录否则无法执行

4、shell脚本

路由器上跑的shell脚本,百度得来的出处忘记了,有需要的可以参考

#!/bin/bash#SMTP配置   #(例子)
#SMTP服务器#smtpserver=smtp.126.com
#邮箱账号#fromaddress=xxxxxx@126.com
#邮箱密码fromaddresspwd=xxxxxxxxxxxxx
#收件人信息#toaddress=xxxxxx@qq.com 英文逗号分隔#SMTP配置
smtpserver=smtp.163.com
fromaddress=xxxx@163.com
fromaddresspwd=xxxxxxxxxxxxx
toaddress=xxxxx@163.com#文件路径,最新ip写入lastwanip.txt 
iptxt="/etc/storage/lastwanip.txt"
#文件路径,邮件正文,写入mail文件
mailtxtpath="/etc/storage/mail.txt"#获取WANIP接口
newwanip=`wget http://members.3322.org/dyndns/getip -q -O -`#如接口获取不到ip,本次取消发送
echo $newwanipif [ x"$newwanip" = "x" ]; thennewwanip=`wget https://ifconfig.me/ip -q -O -`echo $newwanipif [ x"$newwanip" = "x" ]; thenexitfi
fiif [ -f $iptxt ]; thenoldwanip=`cat $iptxt`
elseoldwanip="0.0.0.0"
fi#对比上次IP,如相同则不发邮件,否则发送
echo $oldwanipif [ "$newwanip" = "$oldwanip" ]; thenexit
fi
if [ -f $mailtxtpath ]; thenrm -f $mailtxtpath
fi#配置邮件标题,修改“wanip”和在${newwanip} 后面加参数
#不能修改代码格式,行与行之间必须空格!
cat  <<EOF >>$mailtxtpath
Subject: WANIP:[ ${newwanip} ]路由器型号 = RedMi AC2100IP=    ${newwanip}okTo: $toaddress
From: $fromaddress
EOF#调用系统邮件服务
sendmail -f $fromaddress -t $toaddress -S $smtpserver -au$fromaddress -ap$fromaddresspwd < $mailtxtpath#缓存最新ip地址,写入/etc/storage/lastwanip.txt"
echo $newwanip > $iptxt#打印系统日志,调用logger接口
logger 发现WANIP变化,外网IP= $newwanip 
logger ($fromaddress)已邮件通知($toaddress)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/197175.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

vue解除数据双向绑定

let obj JSON.parse(JSON.stringify(data));例如&#xff0c;table列表中&#xff0c;点击编辑时&#xff0c;可对val进行如上操作来解除双向绑定

Java Swing算术我最棒

内容要求 1) 本次程序设计是专门针对 Java 课程的,要求使用 Java 语言进行具有一定代码量的程序开发。程序的设计要结合一定的算法&#xff0c;在进行代码编写前要能够设计好自己的算法。 本次程序设计涉及到 Java 的基本语法&#xff0c;即课堂上所介绍的变量、条件语句、循…

什么是缓存雪崩、击穿、穿透?

背景 数据一般是存储于数据库中&#xff0c;数据库中的数据都是存在磁盘上的&#xff0c;磁盘读写的速度相较于内存或者CPU中的寄存器来说是非常慢的了。 如果用户的请求都直接访问数据库的话&#xff0c;请求数量一上来&#xff0c;数据库很容易就崩溃了&#xff0c;所以为了…

Flume学习笔记(2)—— Flume进阶

Flume进阶 Flume 事务 事务处理流程如下&#xff1a; Put doPut&#xff1a;将批数据先写入临时缓冲区putListdoCommit&#xff1a;检查channel内存队列是否足够合并。doRollback&#xff1a;channel内存队列空间不足&#xff0c;回滚数据 Take doTake&#xff1a;将数据取…

应用场景丨迭代市政综合管廊监测系统建设

市政综合管廊是指在城市地下建造的隧道空间&#xff0c;将市政、电力、通讯、燃气、给排水等各种管线集于一体&#xff0c;实施统一规划、设计、建设和管理。综合管廊有利于解决反复开挖路面、架空线网密集、管线事故频发等问题&#xff0c;是保障城市运行的重要基础设施和“生…

Dubbo的优雅下线原理分析

文/朱季谦 Dubbo如何实现优雅下线&#xff1f; 这个问题困扰了我一阵&#xff0c;既然有优雅下线这种说法&#xff0c;那么&#xff0c;是否有非优雅下线的说法呢&#xff1f; 这&#xff0c;还真有。 可以从linux进程关闭说起&#xff0c;其实&#xff0c;我们经常使用到杀…

策略模式在数据接收和发送场景的应用(升级版)

1.背景 在数据接收和发送场景打算使用了 if else 进行判断&#xff1a; if("A".equals(system)){ASystem.sync("向A同步数据"); } if("B".equals(system)){BSystem.sync("向B同步数据"); } ... 非常麻烦&#xff0c;需求多了很臃肿&…

C++标准模板(STL)- 类型支持 (类型关系,检查两个类型是否相同,std::is_same)

类型特性 类型特性 类型特性定义一个编译时基于模板的结构&#xff0c;以查询或修改类型的属性。 试图特化定义于 <type_traits> 头文件的模板导致未定义行为&#xff0c;除了 std::common_type 可依照其所描述特化。 定义于<type_traits>头文件的模板可以用不完…

macos 配置ndk环境

选择Android Studio下默认的ndk环境 mac电脑的ndk默认路径一般是 /Users/user_name/Library/Android/sdk/ndk/version_code 其中user_name为自己电脑的用户名&#xff0c;version_code为自己ndk安装的版本号&#xff0c;比如我这里电脑的ndk路径就是 /Users/zhangsan/Libra…

多线程Thread(初阶一:认识线程)

目录 一、引用线程的原因 二、线程的概念 三、进程和线程的区别 四、多线程编程 一、引用线程的原因 多任务操作系统&#xff0c;希望系统能同时运行多个任务。所以会涉及到进程&#xff0c;需要对进程进行管理、调度等。 而单任务操作系统&#xff0c;就完全不涉及到进程…

【漏洞复现】浙大恩特CRM文件上传0day

漏洞描述 浙大恩特客户资源管理系统任意文件上传漏洞 免责声明 技术文章仅供参考,任何个人和组织使用网络应当遵守宪法法律,遵守公共秩序,尊重社会公德,不得利用网络从事危害国家安全、荣誉和利益,未经授权请勿利用文章中的技术资料对任何计算机系统进行入侵操作。利用…

demo(三)eurekaribbonhystrix----服务降级熔断

一、介绍&#xff1a; 1、雪崩&#xff1a; 多个微服务之间调用的时候&#xff0c;假如微服务A调用微服务B和微服务C&#xff0c;微服务B和微服务C又调用其他的微服务&#xff0c;这就是所谓的"扇出"。如果扇出的链路上某个微服务的调用响应的时间过长或者不可用&am…

S7-1200PLC 作为MODBUSTCP服务器通信(多客户端访问)

S7-1200PLC作为MODBUSTCP服务器端通信编程应用,详细内容请查看下面文章链接: ModbusTcp通信(S7-1200PLC作为服务器端)-CSDN博客文章浏览阅读239次。S7-200Smart plc作为ModbusTcp服务器端的通信S7-200SMART PLC ModbusTCP通信(ModbusTcp服务器)_s7-200 modbustcp-CSDN博客文…

flutter开发web应用支持浏览器跨域设置

开发web应用难免会遇到跨域问题&#xff0c;所以flutter设置允许web跨域的设置是要在你的flutter安装路径下面 flutter\bin\cache 找到flutter_tools.stamp文件&#xff0c;然后删除掉&#xff1a;这个文件是临时缓存文件 然后找到 flutter\packages\flutter_tools\lib\src\web…

Linux使用ifconifg命令,没有显示ens33

Linux使用ifconifg命令&#xff0c;没有显示ens33 1.问题2.步骤2.1 查看虚拟机的组件是否启动了2.2 修改网络配置文件 ONBOOT修改为yes2.3 重启网络2.4 修改网络服务配置 3.解决 1.问题 打开虚拟机准备使用xshell连接时发现连接失败&#xff0c;在机器上查看ip发现ens33不现实…

【如何学习Python自动化测试】—— 页面元素定位

接上篇自动化测试环境搭建&#xff0c;现在我们介绍 webdriver 对浏览器操作的 API。 2、 页面元素定位 通过自动化操作 web 页面&#xff0c;首先要解决的问题就是定位到要操作的对象&#xff0c;比如要模拟用户在页面上的输入框中输入一段字符串&#xff0c;那就必须得定位到…

【SQL server】 表结构的约束和维护

表结构的约束和维护 修改表结构 (1)添加列 (2)删除列 (3)修改列alter table 表名 add 新列名 数据类型给员工表添加一列邮箱 alter table People add PeopleMail varchar(200)删除列 alter table People drop column PeopleMain修改列 alter table 表名 alter column 列名 数据…

Sa-Token 整合Java17和SpringBoot

目录 前言引入项目开启登录认证路由拦截鉴权解决兼容问题总结 前言 之前无意中发现Sa-Token权限认证框架&#xff0c;项目十分好用。 项目地址&#xff1a; https://github.com/dromara/sa-token 官网地址&#xff1a; https://sa-token.cc/doc.html#/start/example 我的个人…

助力水泥基建裂痕自动化巡检,基于yolov5融合ASPP开发构建多尺度融合目标检测识别系统

道路场景下的自动化智能巡检、洞体场景下的壁体类建筑缺陷自动检测识别等等已经在现实生活中不断地落地应用了&#xff0c;在我们之前的很多博文中也已经有过很多相关的实践项目经历了&#xff0c;本文的核心目的是想要融合多尺度感受野技术到yolov5模型中以期在较低参数量的情…

迭代新品 | 第四代可燃气体监测仪,守护燃气管网安全快人一步

城市地下市政基础设施是城市有序运行的生命线&#xff0c;事关城市安全、健康运行和高质量发展。近年来&#xff0c;我国燃气事故多发、频发。2020、2021、2022 年分别发生燃气事故668、1140 起、802 起&#xff0c;造成92、106、66 人死亡&#xff0c;560、763、487 人受伤。尤…