1.获取IP的python脚本

sudo vi auto_email_ip.py
#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os
from email.mime.text import MIMEText
import smtplib
from email.header import Header


# check network availability 
while True:
  TIMEOUT=5
  SITE_TO_CHECK="www.baidu.com"
  RET_CODE='curl -I -s --connect-timeout $TIMEOUT $SITE_TO_CHECK -w %{http_code} | tail -n1'
  if [ "x$RET_CODE" == "x200" ]:
    print "Network OK, will send mail..."
    break
  else:
    print "Network not ready, wait..."
    time.sleep(1)
  fi


#call ifconfig
cmd='ifconfig'
m=os.popen(cmd)
t=m.read()
#send result of ifconfigi
m.close()
msg=MIMEText(t,'plain','utf-8')
msg['From']='Raspberry'
msg['To']='desticion'
msg['Subject']=Header('Ip Address Report','utf-8').encode()
#sender email address, replace with your sender email
from_add='sender_mail@xxx.com' 
#receiver email address, replace with your receiver email
to_add='receiver_mail@xxx.com'
#pwd of sender email, if return 550 error code ,please use authorization code
password='your email pwd or authorization code'
#smtp of sender email
smtp_sever='your.smtp.server'
sever=smtplib.SMTP(smtp_sever,25)
sever.set_debuglevel(1)
sever.login(from_add,password)
sever.sendmail(from_add,[to_add],msg.as_string())
sever.quit()

--------

copy auto_email_ip.py 到/etc目录下

2.添加到/etc/rc.local中

sudo vim /etc/rc.local

#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.

python /etc/auto_email_ip.py

exit 0

3.设置执行权限

sudo chmod +x /etc/rc.d/rc.local

sudo systemctl daemon-reload

sudo systemctl list-dependencies multi-user.target | grep rc-local

输出如下内容:

● ├─rc-local.service

4.重启机器查看是否发送邮件成功

 

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐