python实现自动获取IP并发送到邮箱

yipeiwu_com6年前Python基础

树莓派没有显示器,而不想设置固定IP,因为要随身携带外出,每个网络环境可能网段不一样。因此想用python写个脚本,让树莓派开机后自动获取本机ip,并且自动发送到我指定邮箱。(完整源码)

1.获取所有连接的网络接口,比如有线、wifi等接口

def get_ip_address():

  #先获取所有网络接口
  SIOCGIFCONF = 0x8912
  SIOCGIFADDR = 0x8915
  BYTES = 4096     
  sck = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  names = array.array('B',b'\0' * BYTES)
  bytelen = struct.unpack('iL', fcntl.ioctl(sck.fileno(), SIOCGIFCONF, struct.pack('iL', BYTES, names.buffer_info()[0])))[0]
  namestr = names.tostring()
  ifaces = [namestr[i:i+32].split('\0', 1)[0] for i in range(0, bytelen, 32)]

  #再获取每个接口的IP地址
  iplist = []
  for ifname in ifaces:
    ip = socket.inet_ntoa(fcntl.ioctl(sck.fileno(),SIOCGIFADDR,struct.pack('256s',ifname[:15]))[20:24])
    iplist.append(ifname+':'+ip)
  return iplist

2.把IP地址发送到指定邮箱

def ip_send_mail(iptxt):

  #设置收件邮箱
  toaddrs = 'to@mail.com'
  #设置发送邮箱
  fromaddr = 'send@mail.com'

  #设置发送邮箱的账号密码
  username = 'your_sendmail@mail.com' 
  password = 'your_pass'

  #设置SMTP服务器、端口,根据你的邮箱设置,
  server = smtplib.SMTP('smtp.mail.com:25')
  #设置邮件正文,get_ip_address()返回的是list,要转换成str
  ip = '\r\n'.join(iptxt)

  #设置邮件标题和正文
  msg = MIMEText(ip,'plain', 'utf-8')
  msg['Subject'] = 'IP For RaspberryPi'
  msg['From'] = fromaddr
  msg['To'] = toaddrs

  #启动SMTP发送邮件
  server.ehlo()
  server.starttls()
  server.login(username,password)
  server.sendmail(fromaddr, toaddrs, msg.as_string())
  server.quit()

3.最后调用以上函数运行即可

if __name__ == '__main__':

  #获取IP
  iptxt = get_ip_address()
  #将IP存入文件,如果直接发送邮件,这步可以省略。
  ip_save_file(iptxt)  
  #将IP地址发送到指定邮箱
  ip_send_mail(iptxt)

4.设置开机运行

把以上代码都放入一个文件,把文件放到树莓派卡里面,如: /home/pi/get_ip_address.py

给python脚本可执行权限

sudo chmod +x get_ip_address.py

设置系统启动时运行

sudo vi /etc/profile

编辑profile文件,在profile最后面,fi之前添加如下:

python /home/pi/get_ip_address.py

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

DataFrame中去除指定列为空的行方法

一次,笔者在处理数据时想去除DataFrame中指定列的值为空的这一行,采用了如下做法,但是怎么都没有成功: # encoding: utf-8 import pandas as p...

Python做简单的字符串匹配详解

Python做简单的字符串匹配详解  由于需要在半结构化的文本数据中提取一些特定格式的字段、数据辅助挖掘分析工作,以往都是使用Matlab工具进行结构化数据处理的建模,matl...

pytorch 使用单个GPU与多个GPU进行训练与测试的方法

如下所示: device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")#第一行代码 model.t...

python内置函数sorted()用法深入分析

本文实例讲述了python内置函数sorted()用法。分享给大家供大家参考,具体如下: 列表对象提供了sort()方法支持原地排序,而内置函数sorted()不支持原地操作只是返回新的...

Python中字典与恒等运算符的用法分析

本文实例讲述了Python中字典与恒等运算符的用法。分享给大家供大家参考,具体如下: 字典 字典是可变数据类型,其中存储的是唯一键到值的映射。 elements = {"hydrog...