樹莓派開機IP提醒,以及IP更換郵件提醒
來自專欄程序人生
為了方便使用樹莓派,將內網IP發送給指定郵箱
#/bin/env python# -*-coding:utf8-*-import socketimport fcntlimport timeimport structimport smtplibimport urllibimport datetimefrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom email.mime.image import MIMEImage #發送郵件的基本函數,參數依次如下# smtp伺服器地址、郵箱用戶名,郵箱秘密,發件人地址,收件人地址(列表的方式),郵件主題,郵件html內容def sendEmail(smtpserver, username, password, sender, receiver, subject, msghtml): msgRoot = MIMEMultipart(related) msgRoot["To"] = ,.join(receiver) msgRoot["From"] = sender msgRoot[Subject] = subject msgText = MIMEText(msghtml,html,utf-8) msgRoot.attach(msgText) #sendEmail smtp = smtplib.SMTP() smtp.connect(smtpserver) smtp.login(username, password) smtp.sendmail(sender, receiver, msgRoot.as_string()) smtp.quit() # 檢查網路連同性def check_network(): # 試驗5次ping 百度,如果連通就返回True,否則返回False for i in range(0, 5): try: result=urllib.urlopen(http://baidu.com).read() #print result print "Network is Ready!" break except Exception , e: print e print "Network is not ready,Sleep 5s...." time.sleep(5) else: print "Sorry that pi isnt connectted to Internet now" return False return True # 獲得本級制定介面的ip地址def get_ip_address(): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("1.1.1.1",80)) ipaddr=s.getsockname()[0] s.close() return ipaddr if __name__ == __main__: ipold="" while True: if check_network(): ipaddr = get_ip_address() print ipaddr if ipold == ipaddr: time.sleep(120) continue else: ipold = ipaddr now = datetime.datetime.now() time_info = now.strftime(%Y-%m-%d %A %H:%M:%S) send_text = "Boot time: %s
IP addr: %s" % (time_info, ipaddr) sendEmail(smtp.sina.com,username,password,email address,[2661377641@qq.com], Raspberry Pi boot status, send_text) else: print "Sorry that I cant help without network"
推薦閱讀:
※美國十大高科技機場
※自媒體推廣常見的方法
※5G標準聯想站隊的真相——先支持高通後支持華為
※通用處理器的發展(CISC->RISC->???)
※【飛天存儲服務月報】2018年6月刊