手机版
你好,游客 登录 注册 搜索
背景:
阅读新闻

Linux中使用Shell+Python实现监控系统负载+邮件报警

[日期:2012-11-23] 来源:Linux社区  作者:fty8788 [字体:大 中 小]

1. 获取ip、cpu、内存信息

ip使用ifconfig获得

localip=$(ifconfig eth0 | grep 'inet addr' | awk '{print $2}' | cut -f2 -d:)

空闲cpu由mpstat获得

cpuidle=$(mpstat | grep all | awk '{print $11}')

内存使用情况由free获得

freemem=$(free | grep Mem | awk '{print $4}')

totalmem=$(free | grep Mem | awk '{print $2}')

pcent=$(free | grep Mem | awk '{print $4/$2}')

  1. AlertPcent=0.1
  2. AlertCpu=10
  3. msg=
  4. Subject='服务器超载警报'
  5. mailto(){
  6. echo $msg | mail -s $Subject $To
  7. Python sendmail.py $Subject $msg
  8. }
  9. localip=$(ifconfig eth0 | grep 'inet addr' | awk '{print $2}' | cut -f2 -d:)
  10. cpuidle=$(mpstat | grep all | awk '{print $11}')
  11. freemem=$(free | grep Mem | awk '{print $4}')
  12. totalmem=$(free | grep Mem | awk '{print $2}')
  13. pcent=$(free | grep Mem | awk '{print $4/$2}')
  14. echo $localip
  15. echo $cpuidle
  16. echo $freemem
  17. echo $totalmem
  18. echo $pcent
  19. if [ $(echo "$pcent <= $AlertPcent"|bc) = 1 -o $(echo "$cpuidle >= $AlertCpu"|bc) = 1 ]; then
  20. msg='cpu空闲时间为'$cpuidle'%,可用内存剩余'$freemem',总内存为'$totalmem',剩余内存占比'$pcent',低于10%'
  21. echo $msg
  22. mailto
  23. else
  24. echo '系统运行正常'
  25. fi

2. 空闲cpu小于cpu报警阈值或空闲内存比例低于内存报警阈值时发送邮件报警

  1. import smtplib
  2. import sys
  3. from email.mime.text import MIMEText
  4. mailto_list=[""]
  5. mail_host = "smtp.126.com"
  6. mail_user = "monitor_algo"
  7. mail_pass = ""
  8. mail_postfix="126.com"
  9. def send_mail(to_list, sub, context):
  10. me = mail_user + "<"+mail_user+"@"+mail_postfix+">"
  11. msg = MIMEText(context)
  12. msg['Subject'] = sub
  13. msg['From'] = me
  14. msg['To'] = ";".join(to_list)
  15. try:
  16. send_smtp = smtplib.SMTP()
  17. send_smtp.connect(mail_host)
  18. send_smtp.login(mail_user, mail_pass)
  19. send_smtp.sendmail(me, to_list, msg.as_string())
  20. send_smtp.close()
  21. returnTrue
  22. except (Exception, e):
  23. print(str(e))
  24. returnFalse
  25. if __name__=="__main__":
  26. print ("start")
  27. for a in range(1, len(sys.argv)):
  28. print sys.argv[a]
  29. if (True == send_mail(mailto_list,sys.argv[1],sys.argv[2])):
  30. print ("sucess")
  31. else:
  32. print ("failed")

3. 加入crontab定时任务

linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款