Python 脚本如下:
#!/usr/bin/env python #_*_coding:utf-8 _*_ __author__ = ‘lvnian‘ #!/usr/bin env python # coding: utf-8 import MySQLdb as mysql import sys, os db = mysql.connect(user="root",passwd="xxxxx@2015",db="intest",host="192.168.10.12") #数据库连接信息 db.autocommit(True) cur = db.cursor() cur.execute(‘set names utf8‘) dict_list = {} with open(‘access.log‘) as logfin: for line in logfin: arr = line.split(‘ ‘) # 获取ip url 和status ip = arr[0] url = arr[6] status = arr[8] # ip url 和status当key,每次统计+1 dict_list[(ip,url,status)] = dict_list.get((ip,url,status),0)+1 # 转换成列表 ip_list = [(k[0],k[1],k[2],v) for k,v in dict_list.items()] # 按照统计数量排序,排序后保存到数据库。 for insert in sorted(ip_list,key=lambda x:x[3],reverse=True):#如果只想提取前十行的话可以[:10]即可。 print insert #测试用的,可以不要。整个功能是输出一行,然后保存到数据库。 sql = ‘insert loginfo values ("%s","%s","%s","%s")‘ % insert print sql cur.execute(sql)
创建对应的表(在上一篇的基础之上)
use intest; show tables; CREATE TABLE `loginfo` ( `ip` text DEFAULT NULL, `url` longtext DEFAULT NULL, `status` varchar(200) DEFAULT NULL, `count_num` varchar(200) DEFAULT NULL );
脚本执行后数据库内看到的结果如下:
mysql> select * from loginfo where count_num >3 limit 5 ; +----------------+-----------------------+--------+-----------+ | ip | url | status | count_num | +----------------+-----------------------+--------+-----------+ | 121.42.0.85 | / | 200 | 39 | | 121.42.0.37 | / | 403 | 34 | | 121.42.0.39 | / | 403 | 34 | | 222.95.248.220 | HTTP://www.baidu.com/ | 200 | 26 | | 23.251.49.10 | www.baidu.com:443 | 400 | 21 | +----------------+-----------------------+--------+-----------+ 5 rows in set (0.00 sec) mysql>
本文出自 “奋斗吧” 博客,请务必保留此出处http://lvnian.blog.51cto.com/7155281/1845181
原文:http://lvnian.blog.51cto.com/7155281/1845181