创建python脚本文件 auto_send_email.py
#!/usr/bin/python3
import subprocess
import smtplib
from email.mime.text import MIMEText
import datetime
import time
import os
def check_ping():
hostname = "www.baidu.com"
response = os.system("ping -c 1 " + hostname)
# and then check the response...
if response == 0:
pingstatus = True
else:
pingstatus = False
return pingstatus
while True:
if check_ping():
break
time.sleep(1)
# Change to your own account information
# Account Information
to = 'xxxxx@163.com' # Email to send to.
mail_user = 'xxxxx@126.com' # Email to send from.
mail_password = '' # 授权码
smtpserver = smtplib.SMTP('smtp.126.com') # Server to use.
smtpserver.ehlo() # Says 'hello' to the server
smtpserver.starttls() # Start TLS encryption
smtpserver.ehlo()
smtpserver.login(mail_user, mail_password) # Log in to server
today = datetime.date.today() # Get current time/date
arg='ifconfig -a' # Linux command to retrieve ip addresses.
# Runs 'arg' in a 'hidden terminal'.
p=subprocess.Popen(arg, shell=True, stdout=subprocess.PIPE)
data = p.communicate() # Get data from 'p terminal'.
# print(data)
# get ip data
ip_lines = data[0].splitlines()
ips = ""
for ip in ip_lines:
ips += ip.decode("utf-8") + "\n"
# Creates the text, subject, 'from', and 'to' of the message.
msg = MIMEText(ips)
msg['Subject'] = 'IPs For RaspberryPi Ubuntu on %s' % today.strftime('%b %d %Y')
msg['From'] = mail_user
msg['To'] = to
# Sends the message
smtpserver.sendmail(mail_user, [to], msg.as_string())
# Closes the smtp server.
smtpserver.quit()
创建 /etc/rc.local 文件,在/etc/ 目录下,执行 建立的send_email.py 脚本文件,按绝对路径查找python脚本;
给 rc.local 添加可执行权限:
$ sudo chmod +x /etc/rc.local
创建软链接
$ sudo ln -s /lib/systemd/system/rc-local.service /etc/systemd/system/rc-local.service
lib/systemd/system/ 目录下 rc-local.service 文件内添加如下内容:会执行/etc/rc.local 文件
参考:https://blog.csdn.net/weixin_43916516/article/details/133458079