本文实例讲述了Python实现从日志日志中提取ip的方法。分享给大家供大家参考,具体如下:
日志日志内容如下(myjob.log):
124.90.53.68——[05/2月/2018 11:37:07]“GET/图标。ico HTTP/1.1”404 - 61.148.245.145——[05/2月/2018 12:37:44]200 -“GET/HTTP/1.1” 61.148.245.145——[05/2月/2018 12:37:44]”联络/苹果- -图标- 120 x120预作。404 - png HTTP/1.1” 61.148.245.145——[05/2月/2018 12:37:44]“联络/苹果- -图标- 120 x120。404 - png HTTP/1.1” 61.148.245.145——[05/2月/2018 12:37:45]“/apple-touch-icon-precomposed。404 - png HTTP/1.1” 61.148.245.145——[05/2月/2018 12:37:45]“/apple-touch-icon。404 - png HTTP/1.1” 61.148.245.145——[05/2月/2018 12:37:45]”/静态/图标。ico HTTP/1.1”200 - 101.226.33.218——[05/2月/2018 13:07:39]200 -“GET/HTTP/1.1” 101.226.33.219——[05/2月/2018 13:09:46]200 -“GET/HTTP/1.1” 101.226.33.219——[05/2月/2018 13:09:46]“/静态/youkulogo。200 - png HTTP/1.1” 101.226.33.219——[05/2月/2018 13:09:46]“/静态/iqiyi。200 - png HTTP/1.1” 101.226.33.219——[05/2月/2018 13:09:46]“/静态/qqlogo。200 - png HTTP/1.1” 124.202.223.62——[05/2月/2018 14:29:45]200 -“GET/HTTP/1.1” 124.202.223.62——[05/2月/2018 14:29:47]“/静态/youkulogo。200 - png HTTP/1.1” 124.202.223.62——[05/2月/2018 14:29:48]“/静态/qqlogo。200 - png HTTP/1.1” 124.202.223.62——[05/2月/2018 14:29:48]“/静态/iqiyi。200 - png HTTP/1.1” 124.202.223.62——[05/2月/2018 14:29:49]”/静态/图标。ico HTTP/1.1”200 - >之前提取ip:
utf - 8编码: 导入系统 重载(系统) sys.setdefaultencoding (“utf - 8”) 熊猫作为pd导入 进口再保险 导入的时间 进口的要求 time1=time.time () # # # # # #函数功能:能够提取ip地址,并且去重# # # # # # # # # # # # # # # # def read_file (input_file_name output_file_name): _fLog=开放(input_file_name) 9月=' \ n ' ip_list=[] 为每个_fLog: ip=re.findall (r’(& # 63; & lt; ! [\ \ d]。) (& # 63;: \ d {1,3} \) {3} \ d {1,3} (& # 63; ! [\ \ d]。)”, str(每个),re.S) ip_list.append (ip [0]) #列表去重:通过集方法进行处理 id=列表(设置(ip_list)) 打印”共解析ip个数:% s“% len (ids) # #写出数据到本地 #设置输出文件路径=开放(output_file_name,“a”) #。写(“知识产权”+ 9) 对于每个在ids中: 打印每一个 出去了。写(每个+ 9) # #关闭连接 关闭() _fLog.close () 打印”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 () 打印u '总共耗时:“+ str (time2 - time1) +“年代” >之前运行结果:
共解析ip个数:5
引用>
61.148.245.145
124.90.53.68
124.202.223.62
101.226.33.219
101.226.33.218
ip提取完毕~ ~
总共耗时:0.000999927520752 s
过程完成退出代码0http://tools.jb51.net/regex/javascript
http://tools.jb51.net/regex/create_reg
更多关于Python相关内容可查看本站专题:《Python正则表达式用法总结》,《Python数据结构与算法教程》、《Python函数使用技巧总结》,《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》
希望本文所述对大家Python程序设计有所帮助。
Python实现从日志日志中提取ip的方法【正则提取】