Module for Python 3.x analysis log (regular match)

Source: Internet
Author: User

#导入正则模块import reauth="no_shutdown_"‘‘‘分析日志的模块,查找日志中标志性信息产生的次数‘‘‘#定义你需要查找的对象的正则表达式wordcheck#需要分析的日志的路径filesourcedef checklog(wordcheck,filesource): #定义一个空的字典用来存放查询的结果 size={} #异常捕获当文件不存在的时候抛出异常 try: #打开日志文件 file=open(filesource,"r") #循环读取日志文件的每一行 for i in file: #使用re模块的search功能查找当前行是否能和正则匹配 x=re.search(wordcheck,i) #如果匹配到结果则执行if中的代码 if x: #取出查询到的结果 tmp=x.group() #get函数作用是如果字典中取不到key的值则赋一个默认值,也就是每一次查询到一个新的结果就将这个结果作为key vlaue=0新加到字典中 size[tmp]=size.get(tmp,0) #在字典中将value加1,记录一次查找 size[tmp]+=1 #关闭文件 file.close() #如果有异常抛出文件异常 except FileExistsError as e: print(e) #没有异常打印结果 else: return size#测试分析apache访问日志中的所有访问过的ip和次数rs=checklog("(\d+\.){3}\d+","/var/log/httpd/access_log") print(rs)

Results
Because the log results on the test machine are relatively small
{' 127.0.0.1 ': 58, ' 192.168.2.254 ': 10}

Module for Python 3.x analysis log (regular match)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.