树莓派上电发送IP地址到邮箱
2023-12-15 19:56:28
创建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
文章来源:https://blog.csdn.net/weixin_44333597/article/details/134938230
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!