树莓派上电发送IP地址到邮箱

创建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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值