家庭网络是动态的公网IP,虽然用了ddns,但是响应IP变化的速度还是太慢,为了缩短正在连接的时候,发生IP变化导致断开的等待时间,用python写段脚本,挂到旁路由器的系统上,用linux的cron定时执行,发现公网ip变化后发邮件
贴代码如下:
import re
import time
from urllib import request
import smtplib
from email.mime.text import MIMEText
################
## 我发邮件的邮箱地址
myMail = "***@***.com"
################
toMailList= ['***@***.com']
################
# 发邮件的SMTP服务器设置
mySmtp = {"host": "smtp.***.com"
,"user": "***"
,"pwd": "***"
}
################
# 检测外网IP的网站列表
testUrlParams = [{'url': 'http://members.3322.org/dyndns/getip'}
, {'url': 'http://icanhazip.com'}
]
# log文件名
logFileName = 'checkWanIp.log'
# log初始内容
logList = ['']
# 保存上次IP信息的文件
lastInfoFileName = '.lastInfo'
def getWanIpInfo():
ip = None
for urlParam in testUrlParams:
ip = getRequestIpInfo(urlParam)
if ip is None:
continue
else:
return ip
return ip
def getRequestIpInfo(urlParam):
global logList
wanIP = None
try:
ip = str(request.urlopen(urlParam['url']).read())
ip = re.findall(r'\d+.\d+.\d+.\d+', ip)
wanIP = ip[0]
except Exception as e:
logList.append(str(e))
return wanIP
def sendMail(subject, info):
'''
发送邮件到指定的邮箱
subject: 主题
info: 邮件内容
'''
global logList
msg = MIMEText(info)
msg['Subject'] = subject
msg['From'] = myMail
msg['To'] = ";".join(toMailList)
try:
s = smtplib.SMTP();
s.connect(mySmtp['host'])
s.login(mySmtp['user'], mySmtp['pwd'])
s.sendmail(myMail, toMailList, msg.as_string())
s.close()
return True
except Exception as e: \
logList.append(str(e))
return False
def readFile(fileName):
'''
读文件内容
'''
global logList
try:
# 打开文件读取文件内容
f = open(fileName, 'r')
try:
return f.read()
finally:
f.close()
except IOError:
logList.append(
"\r\n" + fileName + " - Can't open the file! Your maybe first run the script, or confirm the Read permission!")
return None
def writeFile(fileName, str):
return writeFileByMode(fileName, str, 'w') # 追加模式
def writeLog(str):
return writeFileByMode(logFileName, str, 'a') # 追加模式
def writeFileByMode(fileName, str, mode):
'''
写文件内容
'''
global logList
if mode is None:
mode = 'w' # 默认写模式
if str is None or str == '':
return False
try:
# 写入文件内容
f = open(fileName, mode)
try:
f.write(str)
return True
finally:
f.close()
except IOError:
logList.append("\r\n" + fileName + " - Can't write the file! Please confirm the write permission")
return False
if __name__ == '__main__':
try:
# 从网站上取得IP
ipInfo = getWanIpInfo()
if ipInfo is None or ipInfo == '':
writeLog("Get Ip Fail!\r\n")
else:
# 读取上次保存的内容
lastInfo = readFile(lastInfoFileName)
# 判断和上次取得的内容是否有变化
if lastInfo != ipInfo:
# 把取得的内容存入文件中,下次用来进行比较
writeFile(lastInfoFileName, ipInfo)
# 取得开始时间字符串
timeStr = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
# 设置邮件主题
subject = '[Get IP](' + timeStr + ')'
# 发送到指定邮箱
sendMail(subject, ipInfo)
writeLog("".join(logList))
except Exception as e: \
writeLog(str(e) + "\r\n")
用pscp传输python脚本文件到旁路由的系统上
pscp -P 端口号 *.py 用户名@公网地址:/usr/local/bin
armbian上操作
sudo chmod +x /usr/local/bin/monitor_ip.py #添加执行权限
crontab -e
/2 * python3 /usr/local/bin/monitor_ip.py #每2分钟执行一次
service cron restart
crontab的默认执行路径为:当前用户的根路径,如果是root用户 就是/root下 不是python脚本所在目录