家庭网络是动态的公网IP,虽然用了ddns,但是响应IP变化的速度还是太慢,为了缩短正在连接的时候,发生IP变化导致断开的等待时间,用python写段脚本,挂到旁路由器的系统上,用linux的cron定时执行,发现公网ip变化后发邮件
    贴代码如下:

    1. import re
    2. import time
    3. from urllib import request
    4. import smtplib
    5. from email.mime.text import MIMEText
    6. ################
    7. ## 我发邮件的邮箱地址
    8. myMail = "***@***.com"
    9. ################
    10. toMailList= ['***@***.com']
    11. ################
    12. # 发邮件的SMTP服务器设置
    13. mySmtp = {"host": "smtp.***.com"
    14. ,"user": "***"
    15. ,"pwd": "***"
    16. }
    17. ################
    18. # 检测外网IP的网站列表
    19. testUrlParams = [{'url': 'http://members.3322.org/dyndns/getip'}
    20. , {'url': 'http://icanhazip.com'}
    21. ]
    22. # log文件名
    23. logFileName = 'checkWanIp.log'
    24. # log初始内容
    25. logList = ['']
    26. # 保存上次IP信息的文件
    27. lastInfoFileName = '.lastInfo'
    28. def getWanIpInfo():
    29. ip = None
    30. for urlParam in testUrlParams:
    31. ip = getRequestIpInfo(urlParam)
    32. if ip is None:
    33. continue
    34. else:
    35. return ip
    36. return ip
    37. def getRequestIpInfo(urlParam):
    38. global logList
    39. wanIP = None
    40. try:
    41. ip = str(request.urlopen(urlParam['url']).read())
    42. ip = re.findall(r'\d+.\d+.\d+.\d+', ip)
    43. wanIP = ip[0]
    44. except Exception as e:
    45. logList.append(str(e))
    46. return wanIP
    47. def sendMail(subject, info):
    48. '''
    49. 发送邮件到指定的邮箱
    50. subject: 主题
    51. info: 邮件内容
    52. '''
    53. global logList
    54. msg = MIMEText(info)
    55. msg['Subject'] = subject
    56. msg['From'] = myMail
    57. msg['To'] = ";".join(toMailList)
    58. try:
    59. s = smtplib.SMTP();
    60. s.connect(mySmtp['host'])
    61. s.login(mySmtp['user'], mySmtp['pwd'])
    62. s.sendmail(myMail, toMailList, msg.as_string())
    63. s.close()
    64. return True
    65. except Exception as e: \
    66. logList.append(str(e))
    67. return False
    68. def readFile(fileName):
    69. '''
    70. 读文件内容
    71. '''
    72. global logList
    73. try:
    74. # 打开文件读取文件内容
    75. f = open(fileName, 'r')
    76. try:
    77. return f.read()
    78. finally:
    79. f.close()
    80. except IOError:
    81. logList.append(
    82. "\r\n" + fileName + " - Can't open the file! Your maybe first run the script, or confirm the Read permission!")
    83. return None
    84. def writeFile(fileName, str):
    85. return writeFileByMode(fileName, str, 'w') # 追加模式
    86. def writeLog(str):
    87. return writeFileByMode(logFileName, str, 'a') # 追加模式
    88. def writeFileByMode(fileName, str, mode):
    89. '''
    90. 写文件内容
    91. '''
    92. global logList
    93. if mode is None:
    94. mode = 'w' # 默认写模式
    95. if str is None or str == '':
    96. return False
    97. try:
    98. # 写入文件内容
    99. f = open(fileName, mode)
    100. try:
    101. f.write(str)
    102. return True
    103. finally:
    104. f.close()
    105. except IOError:
    106. logList.append("\r\n" + fileName + " - Can't write the file! Please confirm the write permission")
    107. return False
    108. if __name__ == '__main__':
    109. try:
    110. # 从网站上取得IP
    111. ipInfo = getWanIpInfo()
    112. if ipInfo is None or ipInfo == '':
    113. writeLog("Get Ip Fail!\r\n")
    114. else:
    115. # 读取上次保存的内容
    116. lastInfo = readFile(lastInfoFileName)
    117. # 判断和上次取得的内容是否有变化
    118. if lastInfo != ipInfo:
    119. # 把取得的内容存入文件中,下次用来进行比较
    120. writeFile(lastInfoFileName, ipInfo)
    121. # 取得开始时间字符串
    122. timeStr = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
    123. # 设置邮件主题
    124. subject = '[Get IP](' + timeStr + ')'
    125. # 发送到指定邮箱
    126. sendMail(subject, ipInfo)
    127. writeLog("".join(logList))
    128. except Exception as e: \
    129. writeLog(str(e) + "\r\n")

    用pscp传输python脚本文件到旁路由的系统上

    1. pscp -P 端口号 *.py 用户名@公网地址:/usr/local/bin

    armbian上操作

    1. sudo chmod +x /usr/local/bin/monitor_ip.py #添加执行权限
    2. crontab -e

    /2 * python3 /usr/local/bin/monitor_ip.py #每2分钟执行一次

    1. service cron restart

    crontab的默认执行路径为:当前用户的根路径,如果是root用户 就是/root下 不是python脚本所在目录