Python parsing nginx logs

Source: Internet
Author: User
Tags python script

Problem: Analyze Nginx logs and find out the source and number of access to up to 10 IP addresses

Using the Python module IP

How to use and: Https://pypi.python.org/pypi/17MonIP

Related Python script:

#!/usr/bin/env Python#coding:utf8#auth:lad#date:2016-12-05#desc:parser the Nginx ' s log,the head of the import sysreload ( SYS) sys.setdefaultencoding ("Utf-8") import ipimport oscnt=10fd = open ("/tmp/ip.txt", "w") Ipstr = Os.popen ("cat/tmp/ Access.log|awk ' {print $6} ' |sort | uniq-c | Sort-nr | Head-10 ") Fd.write (Ipstr.read ()) fd.close () fd1 = open ("/tmp/ip.txt "," r ") fd2 = open ("/tmp/nginx_ip.txt "," w+ ") for I in RA Nge (1,cnt+1): D = fd1.readline () print >> fd2, "Hits:%8s access ip:%16s IP address Source:%20s"% (D.split () [0],d.split () [1],IP.F IND (D.split () [1]) Fd1.close () fd2.close () print "OK"

When you use awk segmentation, you need to consider the format of your own logs and cut them according to format.

Execution Result:

650) this.width=650; "Src=" Http://s3.51cto.com/wyfs02/M01/8B/80/wKioL1hP8h7xhk80AAHrWjU8byU453.jpg-wh_500x0-wm_3 -wmp_4-s_1561238548.jpg "title=" nginx_ip.jpg "alt=" Wkiol1hp8h7xhk80aahrwju8byu453.jpg-wh_50 "/>


This article is from the "Share,open source" blog, so be sure to keep this source http://liqilong2010.blog.51cto.com/3029053/1882400

Python parsing nginx logs

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.