服务器性能监控shell脚本

通过python编写邮件发送工具,通过shell编写性能采集工具进行发现,邮件告警。

1.python邮件脚本

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys
import smtplib
import email.mime.multipart
import email.mime.text

server = 'smtp.163.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'] = 'xxx@163.com'
    msg['To'] = 'xxx@qq.com'
    user = 'xxx'
    pwd = 'xxxxxxxxx'
    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)

将脚本拷贝至/usr/bin/mail,并授予执行权限chmod +x /usr/bin/mail

 

2.shell 监控脚本(内存示例)

#! /bin/bash

mem_limit=0 #内存使用超过90%则报警,为了测试效果,数值为0

function monitor_mem(){
    mem_total=`free |awk 'NR==2{print $2}'`
    mem_use=`free |awk 'NR==2{print $3}'`
    mem_per=`echo "scale=2;$mem_use/$mem_total" |bc -l|cut -d. -f2` #bc&&cut详解 参照下文
    if [ $mem_per -gt $mem_limit ]
        then
            msg="TIME:$(date +%F_%T)
                 HOSTNAME:$(hostname)
                 IPADDR:$(ifconfig |awk 'NR==2{print $2}')
                 MSG:Memory usage exceeds the limit,current value is ${mem_per}%"
            echo $msg
            /usr/bin/mail $msg
    fi
}

monitor_mem &>> /tmp/monitor.log

3.设置计划任务

* * * * *  /root/shell/check.sh

测试结果

 

转载于:https://www.cnblogs.com/sunc/p/7429050.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值