背景: 每次运行树莓派时,不知道ip地址和wifi信息,很是麻烦。如果通过脚本来实现自动发送ip和wifi信息到邮箱,那就很方便了。
首先运行前需要安装yagmail库 sudo pip3 install yagmail
使用者只需要修改邮箱号,邮箱账户名和stmp授权码即可。
#coding=utf-8
import yagmail
import time
import urllib.request
import subprocess
# 检查网络连通性
def check_network():
while True:
try:
result=urllib.request.urlopen('http://www.baidu.com')
print (result)
print ("Network is Ready!")
break
except Exception as e:
print (e)
print ("Network is not ready,Sleep 5s...")
time.sleep(5)
return True
# 运行iwconfig命令行,返回信息
def iwconfig():
result=subprocess.getoutput('iwconfig')
return result
# 运行ifconfig命令行,返回信息
def ifconfig():
result=subprocess.getoutput('ifconfig')
return result
# 发送邮件
def sendEmail():
check_network()
yag = yagmail.SMTP(
user = "xxxxxxxxxx@qq.com", # 发件人邮箱
password='************', # 授权码
host = 'smtp.qq.com')
#邮件内容
contents = [ifconfig(),'#===========分页符===========#', iwconfig()]
yag.send(to = 'xxxxxxxxxx@qq.com',# 收件人邮箱
subject = 'Raspberry Pi 4B', # 邮件主题
contents = contents)
if __name__ == '__main__' :
sendEmail()
stmp授权码是在qq邮箱里面找到,步骤:“设置”>“账户”,下滑找到下图所示。点击“生成授权码”,此时需要验证,验证后将授权码复制即可。
注意:复制粘贴后的码,字母之间没有空格。
比如:“tyeb yyew weew refs”,粘贴后应为“tyebyyewweewrefs”
设置树莓派开机自启动其代码。在这里根目录下创建autoIP.py文件,当然你可以自己拟定名字。
使用sudo vim /etc/rc.local
命令,修改代码如图所示,保存即可。(注意你的路径要正确)。
我这里使用的是vim,你也可以使用nano,个人习惯吧,vim就不介绍怎么使用了。
接着重启系统就可以了,效果如下。