#!/usr/bin/python
"""
    List all active (cgi or php)  apache pages currently being served
 
    Copyright  Afrihost.com (PTY) Ltd 2006
    Original file by: Ed Pascoe <ed@pascoe.co.za>
"""
__author__  = "Ed Pascoe <ed@pascoe.co.za>"
__credits__ = "Afrihost.com -- The best webhosting. Ever."
__version__ = "1.0"
 


import os,sys,urllib,cgi
import re
import HTMLParser

class ApacheStatus(HTMLParser.HTMLParser):
    def __init__(self):
        HTMLParser.HTMLParser.__init__(self)
        self.intable=None
        self.tablecount=0
        self.rowcount=0
        self.rows=[]
        self.thisrow=[]
        self.data=""
    def handle_starttag(self, tag, attrs):
        if not self.intable:
            if tag=="table":  #Lets get to the start of the stuff we are looking for
                self.tablecount += 1
                if (self.tablecount == 1) : self.intable=1
                return
            else: return
        if tag=="tr":
            self.rowcount +=1 
            self.thisrow=[]
        elif tag=="td":
            data=self.data.strip()
            if (data):
                self.thisrow.append(data)
                self.data=""
    def handle_endtag(self, tag):
        if not self.intable: return
        if tag=="tr":
            self.handle_starttag('td',{}) #Apache status is very invalid xml
            if (self.thisrow): 
                if len(self.thisrow) == 13: self.rows.append(self.thisrow) #Append valid rows only
    def handle_data(self,data):
        if not self.intable: return
        self.data += data
    def activerows(self):
        out=[]
        #['105-0', '-', '0/0/4', '.', '0.06', '856', '6', '0.0', '0.00', '0.02', '212.9.22.222', 'www.maesti.co.za', 'GET /adsrv/adimage.php?filename=stopwatch_120x60_491_ef.swfcon']
        #out.append( " " . join(self.rows[0])) #Print header row
        for r in as.rows[1:]:
            try:
                host=r[11]
                call=r[12].split(' ')
                active=0
                if call[0]=="POST": active=1
                elif call[1].find("?") > -1: active=1
                elif call[1].find("cgi") > -1: active=1
                elif call[1].find("php") > -1: active=1
                if active: 
                 out.append("%s %s" % (host," " . join(call)))
            except IndexError: continue #Must be something strange with the current row
        out.append("") #Dummy to force a newline on the end
        return "\n".join(out)
    def loadstatus(self):
        st=urllib.urlopen("http://127.0.0.1/whm-server-status")
        page=st.read()
        self.feed(page)
        self.close()

if __name__=="__main__":
    as=ApacheStatus()
    as.loadstatus()
    print as.activerows()
