#!/usr/bin/env python
import os
import sys
import cgi
import re
import json
import pickle
from datetime import datetime
from datetime import timedelta
#import openpyxl
if sys.argv[-1] == "--test":
logdir="./"
else:
logdir = "/var/log/httpd/"
datefmt = "%Y/%m/%d %H:%M"
form = cgi.FieldStorage()
def machine_name(ip_str):
ip = [int(v) for v in ip_str.split(".")]
if ip_str.startswith("172.29.11"):
if ip[2] == 116: prefix = "GRL"
elif ip[2] == 117: prefix = "ML1"
elif ip[2] == 118: prefix = "ML2"
elif ip[2] == 119: prefix = "HSJ"
else: return ip_str
if prefix != "HSJ" and 151 <= ip[3] <= 150 + 49 or\
prefix == "HSJ" and 151 <= ip[3] <= 150 + 63:
return "%s-%02d" % (prefix, ip[3]-150)
if 220 <= ip[3] <= 220 + 5:
return "%s-K%02d" % (prefix, ip[3]-220)
else: return ip_str
fr = datetime.strptime(form["date"].value + " " + form["from"].value, "%Y %m %d %H:%M")
to = datetime.strptime(form["date"].value + " " + form["to"].value, "%Y %m %d %H:%M")
l = fr + timedelta(7) # a week after
higher = "access_log-%04d%02d%02d"%(l.year, l.month, l.day)
lower = "access_log-%04d%02d%02d"%(fr.year, fr.month, fr.day)
logfiles = [fname for fname in os.listdir(logdir)
if fname.startswith("access_log-") and lower <= fname and fname <=higher]
if not logfiles: logfiles.append('access_log')
maildb = pickle.load(open("name.pickle"))
db = {}
lines = []
for fname in logfiles[-2:]:
with open(logdir + fname) as f:
line = [l for l in f.readlines() if "logonoff" in l]
line = [re.match(r'^([0-9.]*).*\[(\d+/\w+/\d+:\d+:\d+:\d+).*logonoff\?(.*) HTTP', l) for l in line]
line = [l.groups() for l in line if l]
line = [(machine_name(ip), datetime.strptime(date, '%d/%b/%Y:%H:%M:%S'), action)
for ip, date, action in line]
for host, date, action in line:
if host in db:
db[host].append([date,action])
else:
db[host] = [[date,action]]
for machine in db.keys():
candidate = []
active = False
for date, action in db[machine]:
if action.startswith("on:"):
if date < to:
_, id_ = action.split(":")
if id_ in maildb:
date = date.strftime(datefmt)
active = True
candidate.append(
# 0 1 2 3 4
[machine, date, "---", action, id_,
# 5 6
maildb[id_]["no"], maildb[id_]["name"],
# 7 8
maildb[id_]["reading"], maildb[id_]["dep"]])
if action.startswith("off:") or action.startswith("shutdown"):
if candidate:
if not fr < date:
candidate.pop()
elif active and id_ == candidate[-1][4]:
active = False
candidate[-1][2] = date.strftime(datefmt)
lines.extend(candidate)
if not "excel" in form:
print "Content-Type: application/json"
print ""
json.dump(lines, sys.stdout)
else:
pass