基于python3+树莓派开机自启动发送ip和wifi信息

背景: 每次运行树莓派时,不知道ip地址和wifi信息,很是麻烦。如果通过脚本来实现自动发送ip和wifi信息到邮箱,那就很方便了。由此我通过查阅资料,编写了这个脚本,亲测有效,有需要的朋友可以借鉴使用。

使用者只需要修改邮箱号,邮箱账户名和stmp授权码即可

# 导入库
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 = "[email protected]",   #发件人邮箱
        password='**************',  #授权码
        host = 'smtp.qq.com')
    #邮件内容
    contents = [ifconfig(), iwconfig()]
    yag.send(to = '[email protected]',#收件人邮箱
             subject = 'IP_config',  #邮件主题
             contents = contents)

if  __name__ == '__main__' :
    sendEmail()

stmp授权码是在qq邮箱里面找到,步骤:“设置”>“账户”,下滑找到下图所示。点击“生成授权码”,此时需要验证,验证后将授权码复制即可。

注意:复制粘贴后的码,字母之间没有空格。
比如:“tyeb yyew weew refs”,粘贴后应为“tyebyyewweewrefs”
在“设置”找账户
设置树莓派开机自启动其代码。在这里根目录下创建autoIP.py文件,当然你可以自己拟定名字。
在这里插入图片描述
使用sudo vim /etc/rc.local命令,修改代码如图所示,保存即可。(注意你的路径要正确)。
我这里使用的是vim,你也可以使用nano,个人习惯吧,vim就不介绍怎么使用了。

在这里插入图片描述
接着重启系统就可以了,效果如下。

发布了15 篇原创文章 · 获赞 9 · 访问量 2654

猜你喜欢

转载自blog.csdn.net/qq_38413498/article/details/101553572