I'm looking for your opinions on anything that I am doing wrong in the application below, such as best practices, glaringly horrible errors or even just your own personal opinion.
Task: Grab an Nginx access log, ask it some questions and dump responses out to a templated report.
I have removed all comments from this post to keep the reading to a minimum. You can see the full version at GitHub.
#!/usr/bin/python
import datetime
from os import remove
from subprocess import Popen
from subprocess import PIPE
from subprocess import check_output
from string import Template
class NginxReporter():
location = None
template = 'templates/default.html'
html = None
def __init__(self, location=None, template=None, execute=False):
self.location = location
if template:
self.template = template
if execute:
self.parse()
self.output()
self.delete()
def scpdownload(self, remotelocation=None):
if remotelocation:
check_output(['scp', remotelocation, self.location])
def delete(self):
remove(self.location)
def parse(self):
html = {}
codes = Popen("awk '{print $9}' " + self.location +
" | sort | uniq -c | sort -r", shell=True, stdout=PIPE)
html['codes'] = self.build(codes)
statuses = [206, 301, 302, 400, 404, 408, 499, 500]
for status in statuses:
statuslist = Popen("awk '($9 ~ /" + str(status) + "/)' "
+ self.location + " | awk '{print $7}' " +
" | sort | uniq -c | sort -r",
shell=True, stdout=PIPE)
html["http_"+str(status)+"_code"] = self.build(statuslist)
html['generated'] = datetime.datetime.today().strftime('%Y-%m-%d %H:%M')
self.html = html
def build(self, output):
block = ""
while True:
out = output.stdout.read()
if out == '' and output.poll() != None:
break
if out != '':
block = out
return block
def output(self):
file = open(self.template)
block = Template(file.read())
print block.substitute(self.html)
Usage
report = NginxReporter('access.log')
""" report.scpdownload("[email protected]:/path/to/nginx/access.log") """
report.parse()
report.output()