樹莓派啟動後自動傳送本地IP 到指定郵箱
阿新 • • 發佈:2021-01-19
在/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 = '[email protected]' sender = '[email protected]' #發件人郵箱的SMTP伺服器(即sender的SMTP伺服器) smtpserver = 'smtp.qq.com' #發件人郵箱的使用者名稱和授權碼(不是登陸郵箱的密碼) username = '[email protected]' password = '' #([email protected]郵箱的授權碼或者密碼) 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 enablesend_mail_ip.service
啟動 systemctlstartsend_mail_ip.service
檢視狀態 systemctl status send_mail_ip.service
參考: