python統計日誌ip訪問數指令碼

來源:互聯網
上載者:User

python統計日誌ip訪問數指令碼

  1. importre
  2. tudou@Gyyx
  3. f=open("/tmp/a.log","r")
  4. arr={}
  5. lines=f.readlines()
  6. forlineinlines:
  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. ifmatch:
  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. forkeyinarr:
  17. printkey+"->"+str(arr[key])

日誌格式為

[html]view plaincopyprint?
  1. #111.172.249.84--[12/Dec/2011:05:33:36+0800]"GET/images/i/goTop.pngHTTP/1.0"200486"http://wh.xxxx.com/""Mozilla/4.0(compatible;MSIE7.0;WindowsNT6.1;Trident/5.0;SLCC2;.NETCLR2.0.50727;.NETCLR3.5.30729;.NETCLR3.0.30729;MediaCenterPC6.0;.NET4.0C;.NET4.0E)"
  2. #111.172.249.84--[12/Dec/2011:05:33:36+0800]"GET/images/i/goTop.pngHTTP/1.0"200486"http://wh.xxxx.com/""Mozilla/4.0(compatible;MSIE7.0;WindowsNT6.1;Trident/5.0;SLCC2;.NETCLR2.0.50727;.NETCLR3.5.30729;.NETCLR3.0.30729;MediaCenterPC6.0;.NET4.0C;.NET4.0E)"
  3. #111.172.249.85--[12/Dec/2011:05:33:36+0800]"GET/images/i/goTop.pngHTTP/1.0"200486"http://wh.xxxx.com/""Mozilla/4.0(compatible;MSIE7.0;WindowsNT6.1;Trident/5.0;SLCC2;.NETCLR2.0.50727;.NETCLR3.5.30729;.NETCLR3.0.30729;MediaCenterPC6.0;.NET4.0C;.NET4.0E)"
  4. #111.172.249.86--[12/Dec/2011:05:33:36+0800]"GET/images/i/goTop.pngHTTP/1.0"200486"http://wh.xxxx.com/""Mozilla/4.0(compatible;MSIE7.0;WindowsNT6.1;Trident/5.0;SLCC2;.NETCLR2.0.50727;.NETCLR3.5.30729;.NETCLR3.0.30729;MediaCenterPC6.0;.NET4.0C;.NET4.0E)"

輸出結果

111.172.249.86->1
111.172.249.84->2
111.172.249.85->1

注釋:python欄位的setdefault用法為擷取資訊,如果擷取不到的時候就按照他的參數設定該值

[html]view plaincopyprint?
  1. >>>a={}
  2. >>>a['key']='123'
  3. >>>print(a)
  4. {'key':'123'}
  5. >>>print(a.setdefault('key','456'))#顯示a這個字典的'key'值的內容,因為字典有,所以不會去設定它
  6. 123
  7. >>>print(a.setdefault('key1','456'))#顯示a這個字典的'key1'值的內容,因為字典沒有,所以設定為456了
  8. 456
  9. >>>a
  10. {'key1':'456','key':'123'}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.