如何通过树莓派进行公网IP变动后自动邮件通知python,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
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 &
看完上述内容,你们掌握如何通过树莓派进行公网IP变动后自动邮件通知python的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。