分享

python开发监控linux cpu高于指定值的脚本,并统计nginx日志访问记录最高的ip发送邮...

 Levy_X 2017-10-12

最代码经常被莫名的ip攻击到cpu超高导致服务异常,所以通过python实现了一个监控脚本,可以通过crontab每隔1分钟监控cpu的使用率,如果超过指定值70%则统计下nginx访问的最近10000条log中,最高访问记录的10个ip并且发邮件到指定邮箱。

01# encoding=utf8
02 
03import re
04import os
05import commands
06 
07##定时监控cpu,超过80%则统计nginx访问log,将10000行内访问记录数最大的前10名ip和log记录发邮件
08 
09cpu_max = 70
10zuidaima_nginx_log_path = '/usr/local/nginx/logs/www..access.log'
11# cpu 1秒刷新采集5
12sar_cpu_shell = 'sar -u 1 5|awk -F\' \' '{print $3}''
13 
14tail_nginx_shell = 'tail -n 10000 ' zuidaima_nginx_log_path ' |grep -v \'GET /user/reminds\'|grep -v \' 403 \''
15 
16pattern = re.compile(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')
17 
18mail_shell = 'echo \'%s\' | mail -s \'$(echo -e \'%s\nContent-Type: text/html\')\' zuidaima@qq.com'
19 
20 
21def parse_cpu():
22    outputs = commands.getoutput(sar_cpu_shell)
23    cpu_array = outputs.split('\n')
24    ret = cpu_array[len(cpu_array) - 1]
25    return float(ret)
26 
27 
28def tail_date_nginx_log():
29    ret = commands.getoutput(tail_nginx_shell)
30    return ret
31 
32 
33def parse_ip_view(logs):
34    log_list = logs.split('\n')
35    ret = {}
36    ip_log_dic = {}
37    for log in log_list:
38        match = pattern.match(log)
39        if match:
40            ip = match.group(0)
41            if ip in ip_log_dic:
42                ip_view = ip_log_dic[ip]
43            else:
44                ip_view=[]
45            ip_view.append(log)
46            ip_log_dic[ip] = ip_view
47    sorted_ip_log_dic = sorted(ip_log_dic.iteritems(), key=lambda ip_view: len(ip_view[1]), reverse=True)
48    #print type(sorted_ip_log_dic)
49    l = len(sorted_ip_log_dic)
50    if len > 10:
51        l = 10
52    ret = sorted_ip_log_dic[0:l]
53    return ret
54 
55 
56def mail(content):
57    content_str=''
58    for log in content:
59    log0=log[1][0].replace('\'',''')
60    content_str=content_str '  ' log[0] '  ' str(len(log[1])) '  <div style='color:red'>' log0 '</div><br/><br/>'
61    #content_str = ''.join(content).replace('\'',''')
62    mail_shell_str = (mail_shell % (content_str, 'cpu monitor'))
63#    print mail_shell_str
64    commands.getoutput(mail_shell_str)
65 
66 
67def main():
68    cpu = parse_cpu()
69    #print cpu,cpu<cpu_max
70    if (cpu < cpu_max):
71        return
72    logs = tail_date_nginx_log()
73    ip_views = parse_ip_view(logs)
74    mail(ip_views)
75 
76 
77main()

通过crontab定时1分钟调用

1*/1 * * * * python /data/src/zuidaima_script/src/com/zuidaima/script/jarvis.py

运行截图

python开发监控linux cpu高于指定值的脚本,并统计nginx日志访问记录最高的ip发送邮件

最代码是阿里云服务器,自带的python版本是2.4.3,如果语法有兼容性问题,牛牛们可以根据情况做调整。enjoy it

喜欢钢铁侠的jarvis机器人,所以命名为jarvis.py,以后还会有更多类似的jarvis小机器人上线处理你想要的一些繁琐,重复,有规律的任务。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多