歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python寫的日志分析腳本

Python寫的日志分析腳本

日期:2017/3/1 10:27:20   编辑:Linux編程

做運維的朋友剛開始寫python,就用這段分析日志代碼算作入門吧

  1. import re
  2. tudou@Gyyx
  3. f=open("/tmp/a.log","r")
  4. arr={}
  5. lines = f.readlines()
  6. for line in lines:
  7. ipaddress=re.compile(r'^#(((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?))')
  8. match=ipaddress.match(line)
  9. if match:
  10. ip = match.group(1)
  11. if(arr.has_key(ip)):
  12. arr[ip]+=1
  13. else:
  14. arr.setdefault(ip,1)
  15. f.close()
  16. for key in arr:
  17. print key+"->"+str(arr[key])

下面是日志格式

  1. #111.172.249.84 - - [12/Dec/2011:05:33:36 +0800] "GET /images/i/goTop.png HTTP/1.0" 200 486 "http://wh.xxxx.com/" "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)"
  2. #111.172.249.84 - - [12/Dec/2011:05:33:36 +0800] "GET /images/i/goTop.png HTTP/1.0" 200 486 "http://wh.xxxx.com/" "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)"
  3. #111.172.249.85 - - [12/Dec/2011:05:33:36 +0800] "GET /images/i/goTop.png HTTP/1.0" 200 486 "http://wh.xxxx.com/" "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)"
  4. #111.172.249.86 - - [12/Dec/2011:05:33:36 +0800] "GET /images/i/goTop.png HTTP/1.0" 200 486 "http://wh.xxxx.com/" "Mozilla/4.0 (compatible; MSIE 7.0

輸出結果

  1. 111.172.249.86->1
  2. 111.172.249.84->2
  3. 111.172.249.85->1

Copyright © Linux教程網 All Rights Reserved