最代码经常被莫名的ip攻击到cpu超高导致服务异常,所以通过python实现了一个监控脚本,可以通过crontab每隔1分钟监控cpu的使用率,如果超过指定值70%则统计下nginx访问的最近10000条log中,最高访问记录的10个ip并且发邮件到指定邮箱。 07 | ##定时监控cpu,超过 80 %则统计nginx访问log,将 10000 行内访问记录数最大的前 10 名ip和log记录发邮件 |
10 | zuidaima_nginx_log_path = '/usr/local/nginx/logs/www..access.log' |
12 | sar_cpu_shell = 'sar -u 1 5|awk -F\' \' '{print $3}'' |
14 | tail_nginx_shell = 'tail -n 10000 ' zuidaima_nginx_log_path ' |grep -v \'GET /user/reminds\'|grep -v \' 403 \'' |
16 | pattern = re.compile(r '^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}' ) |
18 | mail_shell = 'echo \'%s\' | mail -s \'$(echo -e \'%s\nContent-Type: text/html\')\' zuidaima@qq.com' |
22 | outputs = commands.getoutput(sar_cpu_shell) |
23 | cpu_array = outputs.split( '\n' ) |
24 | ret = cpu_array[len(cpu_array) - 1 ] |
28 | def tail_date_nginx_log(): |
29 | ret = commands.getoutput(tail_nginx_shell) |
33 | def parse_ip_view(logs): |
34 | log_list = logs.split( '\n' ) |
38 | match = pattern.match(log) |
42 | ip_view = ip_log_dic[ip] |
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) |
52 | ret = sorted_ip_log_dic[ 0 :l] |
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' )) |
64 | commands.getoutput(mail_shell_str) |
69 | #print cpu,cpu<cpu_max |
72 | logs = tail_date_nginx_log() |
73 | ip_views = parse_ip_view(logs) |
通过crontab定时1分钟调用 1 | */ 1 * * * * python /data/src/zuidaima_script/src/com/zuidaima/script/jarvis.py |
运行截图 
最代码是阿里云服务器,自带的python版本是2.4.3,如果语法有兼容性问题,牛牛们可以根据情况做调整。enjoy it 喜欢钢铁侠的jarvis机器人,所以命名为jarvis.py,以后还会有更多类似的jarvis小机器人上线处理你想要的一些繁琐,重复,有规律的任务。
|