首页 > 代码库 > 树莓开机发邮件告诉自己ip
树莓开机发邮件告诉自己ip
1 #!/usr/bin/env python 2 # coding=utf-8 3 4 import smtplib 5 import urllib 6 import time 7 import socket 8 import struct 9 import fcntl 10 import array 11 GMAIL_USER = ‘XXXXX@163.com‘ 12 GMAIL_PASS = ‘XXXXXX‘ //需要现在163邮箱里面设置授权安全码 13 SMTP_SERVER = ‘smtp.163.com‘ //之前在这里写了错smtp@163.com,好几天都没有查出来。。。 14 #SMTP_PORT = 465 15 SMTP_PORT = 25 16 recipient = ‘XXXXXX@qq.com‘ 17 def checknet(): //网络连通性 18 for i in range(0,5): 19 try: 20 check = urllib.urlopen(‘http://baidu.com‘).read() 21 print check 22 break 23 except : 24 time.sleep(3) 25 else: 26 return False 27 return True 28 29 def get_ip(): 30 SIOCGIFCONF = 0x8912 31 SIOCGIFADDR = 0x8915 32 BYTES = 4096 33 sck = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) 34 names = array.array(‘B‘,b‘\0‘ * BYTES) //定义数组 35 bytelen = struct.unpack(‘iL‘,fcntl.ioctl(sck.fileno(),SIOCGIFCONF,struct.pack(‘iL‘,BYTES,names.buffer_info()[0])))[0] 36 namestr = names.tostring() 37 ifaces = [namestr[i:i+32].split(‘\0‘,1)[0] for i in range(0,bytelen,32)] 38 ipList = [] 39 for ifname in ifaces: 40 ip = socket.inet_ntoa(fcntl.ioctl(sck.fileno(),SIOCGIFADDR,struct.pack(‘256s‘,ifname[:15]))[20:24]) 41 ipList.append(ifname+‘:‘+ip) 42 return ipList 43 44 if checknet(): 45 try: 46 smtpserver = smtplib.SMTP(SMTP_SERVER,SMTP_PORT) 47 smtpserver.ehlo() 48 smtpserver.starttls() 49 smtpserver.ehlo() 50 smtpserver.login(GMAIL_USER,GMAIL_PASS) 51 header = ‘To:‘+recipient+‘\n‘+‘From:‘+GMAIL_USER 52 header = header + ‘\n‘+ ‘Subject:‘+ ‘IP‘+‘\n‘ 53 ip = ‘\r\n‘.join(get_ip()) 54 msg = header + ‘\n‘ + ip + ‘\n\n‘ 55 smtpserver.sendmail(GMAIL_USER,recipient,msg) 56 smtpserver.close() 57 except: 58 print ‘error for stmp‘ 59 else: 60 print ‘failed‘
好了,脚本保存为send_ip.py,然后在/etc/rc.local里加上下面这行
/usr/bin/python /home/pi/send_ip.py
树莓开机发邮件告诉自己ip
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。