python編寫linux記憶體監控傳送郵件
阿新 • • 發佈:2022-03-11
# _*_ coding: utf-8 _*_ # auther = 林深見鹿,海藍見鯨 import subprocess import datetime def time_stamp(): now_time = datetime.datetime.now() print(now_time) def main(): cmd = ['df', '-h'] p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True) p.wait() res= p.stdout.read() result = res.decode("utf-8") a = result.split() print(a) list = ['95%', '96%', '97%', '98%', '99%', '100%'] for i in a: if i in list: try: send_mail() time_stamp() except: print("郵件傳送失敗".center(50, "-")) time_stamp() else: pass def send_mail(): print("---------------開始傳送郵件---------------") print("開始傳送郵件".center(50, "-")) import smtplib from email.mime.text import MIMEText # 正文 from email.header import Header # 郵件頭 email_username= ' ' email_password = ' ' eamil_address = ' ' email_port = 465 ''' 登入郵箱伺服器 ''' smtp_obj = smtplib.SMTP_SSL(eamil_address, email_port) smtp_obj.login(email_username, email_password) mail_body = '磁碟空間不足,當前磁碟使用率少於5%' msg = MIMEText(mail_body, "plain", "utf-8") msg["Form"] = Header("發件人", "utf-8") # 傳送者 msg["To"] = Header("收件人", "utf-8") # 接受者 msg["Subject"] = Header("磁碟空間不足", "utf-8") # 主題 ''' 傳送 ''' smtp_obj.sendmail("[email protected]", ["[email protected]"], msg.as_string()) if __name__ == '__main__': main()