您好,登錄后才能下訂單哦!
如何通過樹莓派進行公網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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。