[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
在使用的時候把mail文件授予x權限,再複製到/usr/bin
,目錄下看成命令執行。node
[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'] = '1402122292@qq.com' # 發送方的郵箱地址 msg['To'] = 'gonglovepj@gmail.com' # 目的郵箱地址 user = '1402122292@qq.com' # 登錄的用戶 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)