【python ip提取】從log日誌提取ip
阿新 • • 發佈:2019-02-11
log日誌內容如下(myjob.log):
124.90.53.68 - - [05/Feb/2018 11:37:07] "GET /favicon.ico HTTP/1.1" 404 -
61.148.245.145 - - [05/Feb/2018 12:37:44] "GET / HTTP/1.1" 200 -
61.148.245.145 - - [05/Feb/2018 12:37:44] "GET /apple-touch-icon-120x120-precomposed.png HTTP/1.1" 404 -
61.148.245.145 - - [05/Feb/2018 12:37:44] "GET /apple-touch-icon-120x120.png HTTP/1.1" 404 -
61.148.245.145 - - [05/Feb/2018 12:37:45] "GET /apple-touch-icon-precomposed.png HTTP/1.1" 404 -
61.148.245.145 - - [05/Feb/2018 12:37:45] "GET /apple-touch-icon.png HTTP/1.1" 404 -
61.148.245.145 - - [05/Feb/2018 12:37:45] "GET /static/favicon.ico HTTP/1.1" 200 -
101.226.33.218 - - [05/Feb/2018 13:07:39] "GET / HTTP/1.1" 200 -
101.226.33.219 - - [05/Feb/2018 13:09:46] "GET / HTTP/1.1" 200 -
101.226.33.219 - - [05/Feb/2018 13:09:46] "GET /static/youkulogo.png HTTP/1.1" 200 -
101.226.33.219 - - [05/Feb/2018 13:09:46] "GET /static/iqiyi.png HTTP/1.1" 200 -
101.226.33.219 - - [05/Feb/2018 13:09:46] "GET /static/qqlogo.png HTTP/1.1" 200 -
124.202.223.62 - - [05/Feb/2018 14 :29:45] "GET / HTTP/1.1" 200 -
124.202.223.62 - - [05/Feb/2018 14:29:47] "GET /static/youkulogo.png HTTP/1.1" 200 -
124.202.223.62 - - [05/Feb/2018 14:29:48] "GET /static/qqlogo.png HTTP/1.1" 200 -
124.202.223.62 - - [05/Feb/2018 14:29:48] "GET /static/iqiyi.png HTTP/1.1" 200 -
124.202.223.62 - - [05/Feb/2018 14:29:49] "GET /static/favicon.ico HTTP/1.1" 200 -
提取ip:
# encoding: utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import pandas as pd
import re
import time
import requests
time1=time.time()
######函式功能:能夠提取ip地址,並且去重################
def read_file(input_file_name,output_file_name):
_fLog = open(input_file_name)
sep = '\n'
ip_list=[]
for each in _fLog:
ip=re.findall(r'(?<![\.\d])(?:\d{1,3}\.){3}\d{1,3}(?![\.\d])',str(each),re.S)
ip_list.append(ip[0])
# 列表去重:通過set方法進行處理
ids = list(set(ip_list))
print "共解析ip個數:%s "% len(ids)
##寫出資料到本地
# 設定輸出檔案路徑
out = open(output_file_name, "a")
# out.write("ip" + sep)
for each in ids:
print each
out.write(each + sep)
##關閉連線
out.close()
_fLog.close()
print "ip提取完畢~~"
####主函式################
if __name__ == '__main__':
input_file_name = "C:/myjob.log"
output_file_name = "c:/myjob.txt"
read_file(input_file_name, output_file_name)
time2 = time.time()
print u'總共耗時:' + str(time2 - time1) + 's'
執行結果:
共解析ip個數:5
61.148.245.145
124.90.53.68
124.202.223.62
101.226.33.219
101.226.33.218
ip提取完畢~~
總共耗時:0.000999927520752s
Process finished with exit code 0