获取adsl公网地址

 背景
  • 实时获取宽带ADSL公网地址
  • 解决动态域名更新失败,无法获取公网IP
  • 邮件通知变更
 监控脚本
#!/usr/bin/env python
#coding=utf-8
import urllib2,re,sys
import time
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart

def GetWanIP():
respone = urllib2.urlopen('http://ddns.oray.com/checkip',timeout=5)
r = respone.read()
ip = re.search('\d+\.\d+\.\d+\.\d+',r).group()
return ip

def SentMail(LastWanIP,CurrentWanIP,time):
mail_host = 'mail.laohulab.com'
mail_user = 'postmaster'
mail_pass = 'password'
sender = 'postmaster@laohulab.com'
receivers = ['120731842@qq.com','yongjianhu@laohulab.com']

message = MIMEMultipart()
message['From'] = Header(sender)
message['To'] = Header(';'.join(receivers))
message['Subject'] = Header('Adsl IP Update For laohulab.com !','utf-8')
message.attach(MIMEText('Time:%s\nLastWanIP:%s\nCurrentWanIP:%s\n' % (time,LastWanIP,CurrentWanIP), 'plain', 'utf-8'))
att1 = MIMEText(open('adsl.txt','rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
att1["Content-Disposition"] = 'attachment; filename=adsl.txt'
message.attach(att1)
try:
smtpObj = smtplib.SMTP()
smtpObj.connect(mail_host, 25)
smtpObj.login(mail_user,mail_pass)
smtpObj.sendmail(sender, receivers, message.as_string())
print '\033[31;1mSuccess Sent Mail To %s\033[0m' % receivers
except:
print '\033[31;1mFailer Sent Mail To %s\033[0m' % receivers

if __name__ == '__main__':
f = file('adsl.txt','r')
LastWanIP = re.search('\d+\.\d+\.\d+\.\d+',f.read().strip().split()[-1]).group()
f.close()
print LastWanIP
CurrentIP = GetWanIP()
print CurrentIP
if CurrentIP == LastWanIP:
sys.exit('\033[34;1m Current Adsl IP Not Changed For laohulab.com !\033[0m')
else:
t = time.asctime(time.localtime(time.time()))
f = file('adsl.txt','ab')
f.write('%s %s\n' % (t,CurrentIP))
f.flush()
f.close()
SentMail(LastWanIP,CurrentIP,t)
0%