现在的位置: 首页 > 编程语言 > 正文

树莓派 公网IP变动后 自动邮件通知 python

2019年01月11日 编程语言 ⁄ 共 1462字 ⁄ 字号 评论关闭

1. 获取公网IP

 

class Getmyip:
	def getip(self):
		try:
			myip = self.visit("http://www.ip138.com/ip2city.asp")
		except Exception, e1: 
			logging.warning(str(e1))
			
			try:
				myip = self.visit("http://www.whereismyip.com")
			except Exception, e2: 
				logging.warning(str(e2))
				myip = "So sorry!!!"
		return myip
		
	def visit(self,url):
		opener = urllib2.urlopen(url)
#		if url == opener.geturl():
		mystr = opener.read()
		return re.search('\d+\.\d+\.\d+\.\d+',mystr).group(0)

2. 发邮件

def send_mail(to_list,sub,content):  
	mail_host="smtp.163.com"  #设置服务器
	mail_user="aaa"    #用户名
	mail_pass="aaa"   #口令 
	mail_postfix="163.com"  #发件箱的后缀
	
	me="hello"+"<"+mail_user+"@"+mail_postfix + ">"
	msg = MIMEText(content,_subtype='plain',_charset='utf8')  
	msg['Subject'] = sub  
	msg['From'] = me  
	msg['To'] = ";".join(to_list)  
	try:  
		server = smtplib.SMTP()  
		server.connect(mail_host)  
		server.login(mail_user,mail_pass)  
		server.sendmail(me, to_list, msg.as_string())  
		server.close()  
		return True  
	except Exception, e:  
		print str(e)  
		return False  

3. 每半小时检查一次

 

if __name__ == '__main__':  
	
	strLastIP = ''
	logging.info('Starting message')
	while True:
		logging.info('time.sleep begin')
		time.sleep(1600)
		logging.info('time.sleep end')
		getmyip = Getmyip()
		
		logging.info('Getmyip')
		localip = getmyip.getip()
		logging.info('getmyip.getip =' + localip)
		
		if localip == 'So sorry!!!' or localip == '':
			continue
		
 
		
		if  localip == strLastIP :
			logging.info("The same ip : " + localip)
		else:
			
			logging.info( "localip ok : " + localip)  

		
			if send_mail(mailto_list,"IP " + localip, localip):  
				strLastIP = localip
				logging.info( "send ok")  
			else:  
				logging.warning( "send err" ) 

4. 开机启动

编辑  /etc/init.d/rc.local 

python /usr/local/work/sendmyip.py &

抱歉!评论已关闭.