背景: 每次運行樹莓派時,不知道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 = "[email protected]", # 發件人郵箱
password='************', # 授權碼
host = 'smtp.qq.com')
#郵件內容
contents = [ifconfig(),'#===========分頁符===========#', iwconfig()]
yag.send(to = '[email protected]',# 收件人郵箱
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就不介紹怎麼使用了。
接着重啓系統就可以了,效果如下。