使用shell+python指令碼實現系統監控併發送郵件
阿新 • • 發佈:2020-09-03
1、編輯shell指令碼
[root@web03 ~/monitor_scripts]# cat inspect.sh #!/bin/bash # 設定磁碟的閥值 disk_max=90 # 設定監控inode的分割槽 partition="/dev/sda3" # 設定磁碟inode使用率的閥值 disk_inode_use=90 # 這是mem的閥值 mem_max_use=90 # CPU的空閒程度 cpu_less=10 function disk_space_info() { disk_used=$(df -h|grep /$|awk '{print $(NF-1)}'|cut -d% -f1) if [ $disk_used -gt $disk_max ];then Msg="TIME: $(date +%F-%T) HostName: $(hostname) IP: $(hostname -I) Info: 磁碟使用率超過80%,請及時處理!" mail $Msg fi } function disk_inode_use() { inode_used=$(df -i /dev/sda3 |tail -1|awk -F'[ %]+' '{print $5}') if [ $inode_used -gt $disk_inode_use ];then Msg="TIME: $(date +%F-%T) HostName: $(hostname) IP: $(hostname -I) Info: ${partition}分割槽inode使用率超過${disk_inode_use}%,請及時處理!" mail $Msg fi } function monitor_mem() { mem_used=$(free|grep Mem|awk '{printf ($3/$2)*100}'|cut -d. -f1) if [ $mem_used -gt $mem_max_use ];then Msg="TIME: $(date +%F-%T) HostName: $(hostname) IP: $(hostname -I) Info: 記憶體使用率超過${mem_max_use}%,請及時處理!" mail $Msg fi } function monitor_cpu() { cpu_used=$(vmstat 1 3|awk 'NR>=3{x=x+$(NF-2)} END {printf("%u",x/3)}') if [ $cpu_used -lt $cpu_less ];then Msg="TIME: $(date +%F-%T) HostName: $(hostname) IP: $(hostname -I) Info: cpu空閒率小於${cpu_less},請及時處理!" mail $Msg fi } disk_space_info disk_inode_use monitor_mem monitor_cpu
2、編輯python指令碼傳送郵件
在使用的時候把mail檔案授予x許可權,再複製到/usr/bin
,目錄下當作命令執行。
[root@web03 ~/monitor_scripts]# cat mail #!/usr/bin/python # -*- coding: UTF-8 -*- import sys import smtplib import email.mime.multipart import email.mime.text server = 'smtp.qq.com' # 郵箱伺服器 port = '25' # 郵箱伺服器埠 def sendmail(server,port,user,pwd,msg): smtp = smtplib.SMTP() smtp.connect(server,port) smtp.login(user, pwd) smtp.sendmail(msg['from'], msg['to'], msg.as_string()) smtp.quit() print('郵件傳送成功email has send out !') if __name__ == '__main__': msg = email.mime.multipart.MIMEMultipart() msg['Subject'] = '系統監控告警郵件' # 郵件標題 msg['From'] = '[email protected]' # 傳送方的郵箱地址 msg['To'] = '[email protected]' # 目的郵箱地址 user = '[email protected]' # 登陸的使用者 pwd = 'folgrpnvvjfxjijc' # 授權碼 content='%s\n%s' %('\n'.join(sys.argv[1:4]),' '.join(sys.argv[4:])) #格式處理,專門針對我們的郵件格式 txt = email.mime.text.MIMEText(content, _charset='utf-8') msg.attach(txt) sendmail(server,port,user,pwd,msg)