树莓派启动后自动发送本地IP 到指定邮箱

2023-03-10,,

在 /etc/init.d   目录下建立 GetLocalip.py 文件

#coding: utf-8
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import socket
from datetime import datetime
import threading # 获取本地ip
def get_host_ip():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 80))
ip = s.getsockname()[0]
finally:
s.close()
return ip
# 发送邮件
def Send_email():
print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
#收件人和发件人
receiver = 'x@qq.com'
sender = 'xx@qq.com'
#发件人邮箱的SMTP服务器(即sender的SMTP服务器)
smtpserver = 'smtp.qq.com'
#发件人邮箱的用户名和授权码(不是登陆邮箱的密码)
username = 'xx@qq.com'
password = '' #(83xxxx202@qq.com邮箱的授权码或者密码)
mail_title = 'IP 地址'
mail_body = get_host_ip() #创建一个实例
message = MIMEText(mail_body +"\n 时间:"+ datetime.now().strftime("%Y-%m-%d %H:%M:%S") , 'plain', 'utf-8' ) #邮件正文
# (plain表示mail_body的内容直接显示,也可以用text,则mail_body的内容在正文中以文本的形式显示,需要下载)
message ['From'] = sender #邮件上显示的发件人
message['To'] = receiver #邮件上显示的收件人
message['Subject'] = Header( mail_title, 'utf-8' ) #邮件主题
smtp = smtplib.SMTP() #创建一个连接
smtp.connect( smtpserver ) #连接发送邮件的服务器
smtp.login( username, password ) #登录服务器
smtp.sendmail( sender, receiver, message.as_string() ) #填入邮件的相关信息并发送
smtp.quit() if __name__ == "__main__":
# print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
timer = threading.Timer(2, Send_email)
timer.start()
# Send_email()

现在功能基本实现了 ,那么需要树莓派 开机后就执行个文件

编写 一个shell 脚本

#! /bin/sh
python /etc/init.d/GetLocalip.py # 这里需要注意需要用绝对路径
echo "send_ip_mial OK !"
exit 0 ;

我们开机后要调用 shell 脚本 之后调用到我们的 GetLocalip.py 文件

还需要将 shell 文件注册成服务      进入 /etc/systemd/system 目录下

创建 send_mail_ip.service

[Unit]
Description=Send_mail_ip #将本地ip地址发送到指定邮箱
After=network.target # 这里填上你这个脚本所需要的前置service,都在/etc/systemd/system/下【这一项可以不写】 [Service]
ExecStart=/etc/init.d/send_mail.sh
Type=simple
EnvironmentFile=-/erc/init.d/send_mail.sh
ExecReload=sh /etc/init.d/send_mail.sh
KillMode=process
RestartSec=3s
Restart=on-failure [Install]
WantedBy=multi-user.target

重新载入systemd 服务    systemctl daemon-reload

设置开机自启   systemctl enable send_mail_ip.service

启动        systemctl start send_mail_ip.service

查看状态  systemctl status send_mail_ip.service

参考:

Systemd 添加自定义服务(开机自启动) https://www.cnblogs.com/jhxxb/p/10654554.html

树莓派启动后自动发送本地IP 到指定邮箱的相关教程结束。

《树莓派启动后自动发送本地IP 到指定邮箱.doc》

下载本文的Word格式文档,以方便收藏与打印。