一、问题描述
对外服务的Web系统有时候会遭到黑客的DDoS攻击,或者是被第三方软件爬取页面窃取服务,因此需要查找统计出高频请求的来源IP,以便后续处理。
二、处理思路
为避免打草惊蛇,先对最近一段时间内的HTTP服务器日志以及Servlet容器的日志进行静态分析统计,过滤掉合法请求来源后降序展示出统计结果,然后再人工锁定可疑IP。
由于计算量不大,可以使用bash shell命令以及python对日志文件进行统计。如果日后计算量剧增再考虑使用Hadoop MapReduce进行并行处理。
三、具体实现
1.使用grep查找出所有请求IP:
grep -r -E -o "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)" WebLog*
-r是递归搜索
-E选项表示使用grep扩展的正则表达式
-o选项是只显示匹配到的字符串
输出结果形如:
log_file_name:ip_addr
2.使用python统计ip请求次数:
import sys
ipMap = {}
ipFilters = ("10.", "172.")
def isFiltered(inIp):
for ip in ipFilters:
if inIp.startswith(ip):
return True
return False
for line in sys.stdin:
line = line.strip()
if line:
words = line.split(":")
if words and len(words) > 1:
if isFiltered(words[1]):
continue
elif ipMap.get(words[1]):
ipMap[words[1]] += 1
else:
ipMap[words[1]] = 1
for (key, value) in ipMap.items():
print "%-16s %d" % (key,value)
从标准输入流中按行读取数据,过滤掉白名单中的数据,然后放到字典中进行计数,最后把统计结果打印到标准输出流。
3.使用sort进行降序排序:
sort -k 2 -n -r
-k是选取第二列进行排序
-n是使用数字排序,不然会出现9比10大的情况
-r是降序,默认是升序
4.输出前N条记录:
head -n N
5.综合:
grep -r -E -o "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)" WebLog* | python ipcount.py | sort -k 2 -n -r | head -n 20
从100M+的日志文件夹中得出统计结果所需时间在10秒以内,效果还算可以接受。
6.其实也可以全部用bash命令来实现:
grep -E -o "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)" WebLog* | awk '{split($1,a,":");print a[2]}' | sed '/172\..*$/d' | sed '/10\..*$/d' | sort | uniq -c | sort -nr | head -n 20
四、参考资料:
http://www.jbxue.com/LINUXjishu/24950.html
http://www.2cto.com/os/201308/236418.html
http://sjolzy.cn/Python-built-in-string-handling-functions-order.html
http://www.michael-noll.com/tutorials/writing-an-hadoop-mapreduce-program-in-python/
http://www.cnblogs.com/yangyongzhi/archive/2012/09/17/2688326.html
http://www.cnblogs.com/51linux/archive/2012/05/23/2515299.html