花了两天时间,写好一个脚本,在树莓PI 启动的时候,自动发送邮件通知,并且在后台获得公网IP,通过邮件通知。
代码测试完成。
接着想要,加入日志,以及改进邮件发送的过程。
先上源码吧。
#coding: GBK
代码测试完成。
接着想要,加入日志,以及改进邮件发送的过程。
先上源码吧。
#coding: GBK
import smtplib
import re
import urllib.request
import pickle
import os.path
import threading
import time
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
from_addr = 'xxxxxxxx@163.com'
to_addr = 'xxxxxx@qq.com'
db_path = './'
#send mail
def list2Str(list_in):
return ''.join(list_in)
def pickle_test():
with open("mydata.pickle",'wb+') as mydata:
pickle.dump([1,2,'there'], mydata)
with open("mydata.pickle",'rb') as mydata:
a_list = pickle.load(mydata)
## print(a_list)
class MailSender:
_subject = ''
_from = ''
_to = ''
def setSubject(self,subject):
self._subject = Header(subject, 'utf-8')
def setFrom(self,from_addr):
self._from = from_addr
def setTo(self,to_addr):
self._to = to_addr
def send(self,message):
try:
server = smtplib.SMTP('smtp.163.com',25)
server.login(from_addr,'userpasswd')
msg=MIMEMultipart('alternative')
msg['Subject'] = self._subject
msg['From'] = self._from
msg['To'] = self._to
msg['Cc'] = None
content = MIMEText(message, 'plain')
msg.attach(content)
server.sendmail(self._from ,self._to, msg.as_string())
server.quit()
return 'ok'
except smtplib.SMTPAuthenticationError as e:
#print('smtp error '+str(e))
server.quit()
return 'faild'
except smtplib.SMTPSenderRefused as e:
#print('smtp error '+ str(e))
server.quit()
return 'faild'
except smtplib.SMTPDataError as e:
#print('smtp error '+str(e))
server.quit()
return 'faild'
else:
#print('smtp unknow error')
server.quit()
return 'faild'
class IPManager:
_file_name = 'ip_addr.pickle'
def __init__(self, path):
self._file_name = path + self._file_name
#print('path '+self._file_name+' is exsits '+str(os.path.exists(self._file_name)))
if os.path.exists(self._file_name):
return
with open(self._file_name,'wb+') as data:
#print('create ip_addr.pickle')
pickle.dump('0.0.0.0', data)
def getPublicIP(self):
#url_group=['
http://checkip.dyndns.org/','
http://www.ip138.com/ip2city.asp']
myip = self.visit('
http://checkip.dyndns.org')
return str(myip)
def visit(self,url):
response = urllib.request.urlopen(url)
html = response.read()
html = html.decode('utf-8')
#print('html '+html)
ip_addr = re.findall('\d+\.\d+\.\d+\.\d+', html)
return ip_addr
def getRecord(self):
try:
with open(self._file_name,'rb') as data:
ip_addr = pickle.load(data)
#print('load ip '+str(ip_addr)+'in path '+self._file_name)
return str(ip_addr)
# return re.findall('\d+\.\d+\.\d+\.\d+', ip_addr).group(0)
except IOError:
#print('The ip_addr.pickle is missing!')
return 'none'
def record(self, ip):
try:
with open(self._file_name,'wb+') as data:
#print('write ip '+str(ip)+"in "+self._file_name)
pickle.dump(ip, data)
# with open(self._file_name,'rb') as data:
# ip_addr = pickle.load(data)
#print('reload ip '+str(ip_addr)+"in "+self._file_name)
except IOError:
pass
#print('The ip_addr.pickle is missing!')
def chekcIp(mail_sender, ip_manager):
newIp = ip_manager.getPublicIP()
#print("check ip"+newIp)
if newIp != ip_manager.getRecord():
mail_sender.setSubject('IP Changed!')
mail_sender.send('system start at ip '+list2Str(newIp)+" time "+getLocalTime())
ip_manager.record(newIp)
t = threading.Timer(10.0, chekcIp(mail_sender, ip_manager))
t.start()
def getLocalTime():
return time.strftime('%Y-%m-%d,%H:%M:%S',time.localtime(time.time()))
if __name__ == '__main__':
print("system start")
sender = MailSender()
sender.setFrom(from_addr)
sender.setTo(to_addr)
sender.send('system start'+getLocalTime())
manager = IPManager(db_path)
t = threading.Timer(500.0, chekcIp(sender, manager))
t.start()