Exemple #1
0
 def template(self, file='setup.html'):
    """ overwrite the template function in cgi_app """
    proc = TemplateProcessor()
    temp = TemplateManager(precompile=0).prepare("templates/%s" % file)
    for key in self.globals.keys():
       proc.set(key,self.globals[key])
    body = proc.process(temp)
    return body
Exemple #2
0
def stats_table(root):
    raw_stats = honeyd.stats_network()

    stats = []

    # Convert the dictionary into something that the template manager
    # can understand.
    for key in raw_stats.keys():
        minute = humanize(raw_stats[key][0], '/s')
        hour = humanize(raw_stats[key][1], '/s')
        day = humanize(raw_stats[key][2], '/s')

        stats.append({"name": key, "minute": minute, "hour": hour, "day": day})

    template = TemplateManager().prepare(root + "/templates/status_stats.tmpl")
    tproc = TemplateProcessor(0)

    tproc.set("title", "Honeyd Statistics")
    tproc.set("explanation", ("This table shows current statistics collected "
                              "by Honeyd."))
    tproc.set("Stats", stats)

    content = tproc.process(template)

    return content
Exemple #3
0
def status_connections(root, which):
    connections = honeyd.status_connections(which.lower())

    if not len(connections):
        return "There are currently no active %s connections." % which.upper()

    for connection in connections:
        id = "%s,%s,%d,%s,%d" % (which.lower(), connection['src'],
                                 connection['sport'], connection['dst'],
                                 connection['dport'])
        connection['id'] = urllib.quote(id)

    template = TemplateManager().prepare(root +
                                         "/templates/status_connections.tmpl")
    tproc = TemplateProcessor(0)

    tproc.set("title", "Active %s Connections" % which.upper())
    tproc.set(
        "explanation",
        "This table shows the currently active %s connections" % which.upper())
    tproc.set("Connections", connections)

    content = tproc.process(template)

    return content
Exemple #4
0
def render_template(template_file,data):
    from htmltmpl import TemplateManager, TemplateProcessor

    mgr = TemplateManager()
    template = mgr.prepare(template_file)
    tproc = TemplateProcessor(global_vars=1)
    
    for key in data.keys():
        tproc.set(key,data[key])

    print tproc.process(template)
Exemple #5
0
def stats_table(root):
    raw_stats = honeyd.stats_network()

    stats = []

    # Convert the dictionary into something that the template manager
    # can understand.
    for key in raw_stats.keys():
        minute = humanize(raw_stats[key][0], '/s')
        hour = humanize(raw_stats[key][1], '/s')
        day = humanize(raw_stats[key][2], '/s')
            
        stats.append({ "name" : key,
                       "minute" : minute,
                       "hour" : hour,
                       "day" : day })

    template = TemplateManager().prepare(root +
                                         "/templates/status_stats.tmpl")
    tproc = TemplateProcessor(0)

    tproc.set("title", "Honeyd Statistics")
    tproc.set("explanation",("This table shows current statistics collected "
                             "by Honeyd."))
    tproc.set("Stats", stats)

    content = tproc.process(template)

    return content
 def main(self):
     while True:                
         while self.dataReady("channels-inbox"):
             data = self.recv("channels-inbox")
             self.channels.append(data)
             
         while self.dataReady("feeds-inbox"):
             data = self.recv("feeds-inbox")
             self.feeds.append(data)
             
         while self.dataReady("posts-inbox"):
             data = self.recv("posts-inbox")
             self.posts.append(data)
             
         while self.dataReady("config-inbox"):
             data = self.recv("config-inbox")
             self.config = data
         
         mustStop, providerFinished = self.checkControl()
         if mustStop:
             self.send(mustStop,"signal")
             return
         
         if providerFinished is not None and self.config is not None:
             tproc = TemplateProcessor(html_escape=0)
             template = self.prepareTemplate()
             yield 1
             
             self.fillTemplate(tproc)
             result = tproc.process(template)
             yield 1
             
             self.send(self.getOutputFileName(), 'create-output')
             yield 1
             
             self.send(result, "outbox")
             yield 1
             
             self.send(producerFinished(self), "signal")
             if self.VERBOSE:
                 print "File written %s" % self.getOutputFileName()
             return
             
         if not self.anyReady():
             self.pause()
             
         yield 1
Exemple #7
0
    def main(self):
        while True:
            while self.dataReady("channels-inbox"):
                data = self.recv("channels-inbox")
                self.channels.append(data)

            while self.dataReady("feeds-inbox"):
                data = self.recv("feeds-inbox")
                self.feeds.append(data)

            while self.dataReady("posts-inbox"):
                data = self.recv("posts-inbox")
                self.posts.append(data)

            while self.dataReady("config-inbox"):
                data = self.recv("config-inbox")
                self.config = data

            mustStop, providerFinished = self.checkControl()
            if mustStop:
                self.send(mustStop, "signal")
                return

            if providerFinished is not None and self.config is not None:
                tproc = TemplateProcessor(html_escape=0)
                template = self.prepareTemplate()
                yield 1

                self.fillTemplate(tproc)
                result = tproc.process(template)
                yield 1

                self.send(self.getOutputFileName(), 'create-output')
                yield 1

                self.send(result, "outbox")
                yield 1

                self.send(producerFinished(self), "signal")
                if self.VERBOSE:
                    print "File written %s" % self.getOutputFileName()
                return

            if not self.anyReady():
                self.pause()

            yield 1
Exemple #8
0
    def __init__(self, template, debug=0):
        """ Constructor.             

            @header __init__(template, debug=0)
           
            @param template String containing template data.
            
            @param debug Enable or disable debugging messages.
            This optional parameter can be used to enable or disable debugging
            messages which are printed to stderr. By default debugging
            messages are disabled.
        """
        self._debug = debug
        self._classes = []
        self._functions = []
        self._class = {}
        self._template = TemplateCompiler().compile_string(template)
        self._tproc = TemplateProcessor(html_escape=0)
Exemple #9
0
def config_ips(root):
    ips = honeyd.config_ips()

    template = TemplateManager().prepare(root + "/templates/config_ip.tmpl")
    tproc = TemplateProcessor(0)

    tproc.set("title", "Bound IP addresses")
    tproc.set(
        "explanation", "This table shows the IP addresses of the " +
        "currently configured virtual honeypots.")
    tproc.set("Ips", ips)

    content = tproc.process(template)

    return content
Exemple #10
0
def config_ips(root):
    ips = honeyd.config_ips()

    template = TemplateManager().prepare(root + "/templates/config_ip.tmpl")
    tproc = TemplateProcessor(0)

    tproc.set("title", "Bound IP addresses")
    tproc.set("explanation", "This table shows the IP addresses of the " +
                                "currently configured virtual honeypots.")
    tproc.set("Ips", ips)

    content = tproc.process(template)

    return content
Exemple #11
0
    def __init__(self, template, debug=0):
        """ Constructor.             

            @header __init__(template, debug=0)
           
            @param template String containing template data.
            
            @param debug Enable or disable debugging messages.
            This optional parameter can be used to enable or disable debugging
            messages which are printed to stderr. By default debugging
            messages are disabled.
        """
        self._debug = debug
        self._classes = []
        self._functions = []
        self._class = {}        
        self._template = TemplateCompiler().compile_string(template)
        self._tproc = TemplateProcessor(html_escape=0)            
Exemple #12
0
def tmpl(name, sid=None):
    if not name.endswith(".tmpl"):
        name = name + ".tmpl"

    name = os.path.join(tmpldir, name)

    template = TemplateManager().prepare(name)
    tproc = TemplateProcessor()

    if sid: tproc.set('sid', sid)
    tproc.set('css_path', css_path)

    return template, tproc
Exemple #13
0
   def html_template(self,compiled_template,data={}):
      """ replaces a mode in htmltmpl """
      from htmltmpl import TemplateManager, TemplateProcessor

      mgr = TemplateManager()
      tproc = TemplateProcessor(html_escape=0)

      for key in self.__globals__.keys():
         tproc.set(key,self.__globals__[key])

      for key in data.keys():
         tproc.set(key,data[key])

      return tproc.process(compiled_template)
Exemple #14
0
def status_connections(root, which):
    connections = honeyd.status_connections(which.lower())

    if not len(connections):
        return "There are currently no active %s connections." % which.upper()

    for connection in connections:
        id = "%s,%s,%d,%s,%d" % (which.lower(),
                                   connection['src'], connection['sport'],
                                   connection['dst'], connection['dport'])
        connection['id'] = urllib.quote(id)

    template = TemplateManager().prepare(root +
                                         "/templates/status_connections.tmpl")
    tproc = TemplateProcessor(0)

    tproc.set("title", "Active %s Connections" % which.upper())
    tproc.set("explanation",
              "This table shows the currently active %s connections" % which.upper())
    tproc.set("Connections", connections)

    content = tproc.process(template)

    return content
Exemple #15
0
    def html_template(self,template_file,data={}):
        """ replaces the variables in the template with values specified in
        a dictionary.

        uses the htmltmpl module. see the documentation for htmltmpl for more info.

        """
        from htmltmpl import TemplateManager, TemplateProcessor
        mgr = TemplateManager()
        template = mgr.prepare("%s/%s" % (self.template_dir,template_file))
        tproc = TemplateProcessor(html_escape=0)
        for key in self.__globals__.keys():
            tproc.set(key,self.__globals__[key])

        for key in data.keys():
            tproc.set(key,data[key])

        return tproc.process(template)
Exemple #16
0
   def template(self, template_file, data={}, nav=True):
      """ overwrite the template function in cgi_app """
      from htmltmpl import TemplateCompiler, TemplateProcessor, TemplateManager

      # get the configuration
      self.GetConfigs(data)

      # get the navigation
      self.GetNavs(data)

      # set compilers, processors, and managers
      temp = TemplateManager(precompile=0).prepare("%s/%s" % (self.template_dir, template_file))
      proc = TemplateProcessor()
      cmpl = TemplateCompiler()

      # set keys
      for key in self.__globals__.keys():
         proc.set(key,self.__globals__[key])

      # set vars
      for key in data.keys():
         proc.set(key,data[key])

      # make body to be put in to the string to be compiled
      try:
         body = proc.process(temp)
      except:
         body = ''

      # make string to compile
      tempStr = ''

      # add nav bars
      tempStr += open("%s/%s" % (self.template_dir, "inc/header.html")).read()
      tempStr += body
      tempStr += open("%s/%s" % (self.template_dir, "inc/footer.html")).read()

      # return a TemplateManager object
      return self.html_template(cmpl.compile_string(tempStr), data)
Exemple #17
0
#!/usr/bin/env python

TEST = "compiled"

import sys
import os
sys.path.insert(0, "..")

from htmltmpl import TemplateManager, TemplateProcessor

man = TemplateManager(precompile = 1, debug = "debug" in sys.argv)
template = man.prepare(TEST + ".tmpl")
tproc = TemplateProcessor(debug = "debug" in sys.argv)

#######################################################

def fill(tproc):
    tproc.set("title", "Template world.")
    tproc.set("greeting", "Hello !")
    tproc.set("Boys", [
        { "name" : "Tomas",  "age" : 19 },
        { "name" : "Pavel",  "age" : 34 },
        { "name" : "Janek",  "age" : 67 },
        { "name" : "Martin", "age" : 43 },
        { "name" : "Viktor", "age" : 78 },
        { "name" : "Marian", "age" : 90 },
        { "name" : "Prokop", "age" : 23 },
        { "name" : "Honzik", "age" : 46 },
        { "name" : "Brudra", "age" : 64 },
        { "name" : "Marek",  "age" : 54 },
        { "name" : "Peter",  "age" : 42 },
Exemple #18
0
# 生成文档的title和最新更新时间列表
for file_path,category in article_category.items():
    fd = open(file_path)
    fd.seek(0)
    title = fd.readline()
    keyword = fd.readline()
    uuid = fd.readline()
    fd.close()
    article_title[file_path] = title
    article_keyword[file_path] = keyword
    article_uuid[file_path] = uuid
    article_lastmodify[file_path] = "%d" % os.stat(file_path).st_mtime

#============ 生成首页 =============#
template = TemplateManager().prepare(index_html_template)
tproc = TemplateProcessor(html_escape=0)

# Create the 'Menuitem' loop.
Menuitems = []
for category,cn_name in site_category.items():
    if category in article_category.values():
        menuitem = {}
        menuitem["menu_href"] = "/%s/index.html" % (category)
        menuitem["menu_name"] = cn_name
        Menuitems.append(menuitem)


# 首页显示最新的一篇文章内容
index_article = []
# create new article list
Newarticles = []
Exemple #19
0
#!/usr/bin/env python

import sys
import gettext
import locale
sys.path.insert(0, "../..")
from htmltmpl import TemplateManager, TemplateProcessor

locale.setlocale(locale.LC_MESSAGES, "en_US")
gettext.bindtextdomain("test", "./locale")
gettext.textdomain("test")

man = TemplateManager(precompile = 0, gettext = 1, debug = 1)
tmpl = man.prepare("gettext.tmpl")
tproc = TemplateProcessor(debug = 1)
tproc.set("title", "Gettext test page")
print(tproc.process(tmpl))

    def __init__(self, fname=None, htmlescape=0):

        self.tmpl_fname = fname
        dict.__init__(self)
        TemplateProcessor.__init__(self, html_escape=htmlescape)
Exemple #21
0
from htmltmpl import TemplateManager, TemplateProcessor

# Compile or load already precompiled template.
template = TemplateManager().prepare("template.tmpl")
tproc = TemplateProcessor()

# Set the title.
tproc.set("title", "Our customers")

# Create the 'Customers' loop.
customers = []

# First customer.
customer = {}
customer["name"] = "Joe Sixpack"
customer["city"] = "Los Angeles"
customer["new"] = 0
customers.append(customer)

# Second customer.
customer = {}
customer["name"] = "Paul Newman"
customer["city"] = "New York"
customer["new"] = 1
customers.append(customer)

tproc.set("Customers", customers)

# Print the processed template.
print(tproc.process(template))
Exemple #22
0
import time
import support
from htmltmpl import TemplateManager, TemplateProcessor

self.send_response(200)
self.send_header("Content-Type", "text/html")
self.send_nocache()
self.end_headers()

# Process commands given to us
message = support.parse_query(self.query)

# Compile or load already precompiled template.
template = TemplateManager().prepare(self.root+"/templates/index.tmpl")
tproc = TemplateProcessor(0)

# Set the title.
tproc.set("title", "Honeyd Configuration Interface")

content = "Welcome to the Honeyd Configuration Interface.<p>"
content += support.config_table()
content += "<p>"
content += support.config_ips(self.root)

if message:
    tproc.set("message", message)
tproc.set("content", content)
tproc.set("uptime", support.uptime())

# Print the processed template.
self.wfile.write(tproc.process(template))
Exemple #23
0
class Easydoc:
    """ Autogenerate documentation from docstrings.    

        This class provides all the functionality of easydoc. You can
        subclass it and override its processing methods module(),
        mclass() and method() to customize its behaviour.
        
        You also can easily use your own template to modify the output
        in any way you need. Output colors can be customized via
        parameters.
    """
    def __init__(self, template, debug=0):
        """ Constructor.             

            @header __init__(template, debug=0)
           
            @param template String containing template data.
            
            @param debug Enable or disable debugging messages.
            This optional parameter can be used to enable or disable debugging
            messages which are printed to stderr. By default debugging
            messages are disabled.
        """
        self._debug = debug
        self._classes = []
        self._functions = []
        self._class = {}
        self._template = TemplateCompiler().compile_string(template)
        self._tproc = TemplateProcessor(html_escape=0)

    def process(self,
                module,
                bgcolor,
                textcolor,
                linkcolor,
                methodbg,
                with_hidden=0):
        """ Create documentation for a module.

            @header process(module, bgcolor, textcolor, linkcolor,
                            with_hidden=0)
            @return String containing the resulting HTML documentation.
            
            @param module Filename of the module to document.
            The module must be specified as filename. The module is not
            imported nor executed, only parsed.

            @param bgcolor Set background color.
            Accepts any valid CSS color value.

            @param textcolor Set text color.
            Accepts any valid CSS color value.

            @param linkcolor Set color of hyperlinks.
            Accepts any valid CSS color value.
            
            @param with_hidden Do not exclude hidden sections from output.
            This optional parameter can be used to force inclusion of
            hidden sections in the resulting documentation. Hidden sections
            are by default not included.            
        """
        mdict = {}
        self._tproc.set("bgcolor", bgcolor)
        self._tproc.set("textcolor", textcolor)
        self._tproc.set("linkcolor", linkcolor)
        self._tproc.set("methodbg", methodbg)

        # Parse the module.
        ast = parser.suite(open(module).read())
        module_info = easydocp.ModuleInfo(ast.totuple())
        self.module(module_info.get_docstring())

        # Class info.
        for mclass in module_info.get_class_names():
            class_info = module_info.get_class_info(mclass)
            if self.mclass(mclass, class_info.get_docstring(), with_hidden):
                # The class should be included in the output.
                self._class["Methods"] = []
                for method in class_info.get_method_names():
                    method_info = class_info.get_method_info(method)
                    self.method(mclass, method, method_info.get_docstring(),
                                with_hidden)
                self.DEB("Finished class: " + mclass)
                self._classes.append(copy.copy(self._class))
            self._class.clear()
        self._tproc.set("Classes", self._classes)

        # Functions info.
        for function in module_info.get_function_names():
            function_info = module_info.get_function_info(function)
            self.method("", function, function_info.get_docstring(),
                        with_hidden)
        self._tproc.set("Functions", self._functions)

        return self._tproc.process(self._template)

    ##############################################
    #              PRIVATE METHODS               #
    ##############################################

    def module(self, doc):
        """ Process docstring of a module. 
            @hidden
        """
        short, detailed, statements = self.parse(doc)
        self.DEB("Module: short: " + short)
        self.DEB("Module: statements: " + pprint.pformat(statements))

        self._tproc.set("short", short.strip())
        self._tproc.set("Detailed", self.detailed(detailed))

        # Statements.
        requires = []
        for statement in statements:
            param, data = statement
            if param == "name":
                self._tproc.set("name", data.strip())
                self.DEB("Module: name: " + data)
            elif param == "version":
                self._tproc.set("version", data.strip())
            elif param == "website":
                self._tproc.set("website", data.strip())
            elif param == "author-name":
                self._tproc.set("author-name", self.mangle(data))
            elif param == "author-email":
                self._tproc.set("author-email", data.strip())
            elif param == "license-name":
                self._tproc.set("license-name", data.strip())
            elif param == "license-url":
                self._tproc.set("license-url", data.strip())
            elif param == "require":
                requires.append({"require": self.mangle(data)})
            else:
                self.warn("Unknown statement: " + param)
        self._tproc.set("Requires", requires)

    def mclass(self, name, doc, with_hidden=0):
        """ Process docstring of a class.
            @hidden
        """
        short, detailed, statements = self.parse(doc)
        self.DEB("Class: " + name + ": short: " + short)
        self.DEB("Class: " + name + ": statements: " + \
                 pprint.pformat(statements))

        self._class["name"] = name
        self._class["short"] = short.strip()
        self._class["Detailed"] = self.detailed(detailed)

        for statement in statements:
            param, data = statement
            if param == "hidden":
                if not with_hidden:
                    self.DEB("Class: " + name + ": HIDDEN")
                    return 0
            else:
                self.warn("Unknown statement: " + param)
        else:
            return 1

    def method(self, mclass, name, doc, with_hidden=0):
        """ Process docstring of a method.
            @hidden
        """
        method = {}
        short, detailed, statements = self.parse(doc)
        if mclass:
            self.DEB("Method: " + name + ": short: " + short)
            self.DEB("Method: " + name + ": statements: " + \
                     pprint.pformat(statements))
        else:
            self.DEB("Function: " + name + ": short: " + short)
            self.DEB("Function: " + name + ": statements: " + \
                     pprint.pformat(statements))

        method["name"] = name
        method["class"] = mclass
        method["short"] = short.strip()
        method["Detailed"] = self.detailed(detailed)

        parameters = []
        for statement in statements:
            param, data = statement
            if param == "hidden":
                if not with_hidden:
                    self.DEB("Method: " + name + ": HIDDEN")
                    return 0
            elif param == "header":
                header = data.strip()
                header = re.sub(r"\s+", " ", header)
                method["header"] = header
            elif param == "return":
                method["return"] = self.mangle(data)
            elif param == "param":
                parameter = {}

                # Split the data into first line and rest.
                lines = data.splitlines(KEEP_NEWLINES)
                first_line = lines[0].strip()

                # Split the first line into name and short description
                # of the parameter.
                fsplit = first_line.split(" ", 1)
                if len(fsplit) == 2:
                    pname, pshort = fsplit
                elif len(fsplit) == 1:
                    pname = fsplit[0]
                    pshort = ""
                else:
                    pname = ""
                    pshort = ""

                if len(lines) > 1:
                    pdetailed = string.join(lines[1:])
                else:
                    pdetailed = ""

                self.DEB("Parameter: " + pname.strip())
                parameter["name"] = pname.strip()
                parameter["short"] = pshort.strip()
                parameter["Detailed"] = self.detailed(pdetailed)
                parameters.append(parameter)
            else:
                self.warn("Unknown statement: " + param)
        else:
            method["Parameters"] = parameters
            if mclass:
                self._class["Methods"].append(method)
            else:
                self._functions.append(method)
            return 1

    def parse(self, doc):
        """ Parse a docstring.            
            
            Split the docstring into short description, detailed description
            and a list containing a tuple for every statement. The first
            element of the tuple is name of the statement, the second is the
            data of the statement.
            
            @hidden
        """
        short = ""
        detailed = ""
        statements = []
        if not doc:
            return short, detailed, statements

        doc = doc.replace("\"\"\"", "")

        rc = re.compile(r"""
            ^\s*(@)([-\w]+)
        """, re.VERBOSE | re.MULTILINE)
        tokens = rc.split(doc)
        len_tokens = len(tokens)
        i = 0
        skip_param = 0
        while 1:
            if i == len_tokens:
                break
            if skip_param:
                skip_param = 0
                i += 2
                continue
            token = tokens[i]
            if token == "@":
                skip_param = 1
                param = tokens[i + 1]
                data = tokens[i + 2]
                statements.append((param, data))
            else:
                if not short:
                    lines = token.splitlines(KEEP_NEWLINES)
                    short = lines[0]
                    if len(lines) > 1:
                        detailed = string.join(lines[1:])
            i += 1
        return short, detailed, statements

    def DEB(self, str):
        """ Print debugging message to stderr if debugging is enabled.
            @hidden
        """
        if self._debug: print >> sys.stderr, str

    def warn(self, warning):
        """ Print a warning to stderr.
            @hidden
        """
        print >> sys.stderr, warning

    def mangle(self, str):
        """ Strip leading and trailing whitespace. Convert URL to hyperlink.
            @hidden
        """
        str = str.strip()
        return re.sub(r"\[ (http://.*?) \]", r'<a href="\1">\1</a>', str)

    def detailed(self, str):
        """ Process detailed descritpion.
            
            Split it into paragraphs at empty lines.
            Return list of the paragraphs.
            
            @hidden
        """
        paragraphs = []
        rc = re.compile(r"^\s*$", re.MULTILINE)  # allow any whitespace
        for p in rc.split(str):
            if re.search(r"\S", p):
                paragraphs.append({"paragraph": self.mangle(p)})
        return paragraphs
Exemple #24
0
def summarize():
    global success_counter, failure_counter, blow_counter, skip_counter
    global cur_name
    global report_entry_set, map_stats_entry_set

    print
    print 'Test Script: %s' % cur_name
    print 'Succeeded: %d' % success_counter
    print 'Failed:    %d (%d blew exceptions)' \
          % (failure_counter+blow_counter, blow_counter)
    print 'Skipped:   %d' % skip_counter
    print

    # find whether we are in test root dir or one level up
    if os.path.exists(os.path.join("..", "SummaryReport.tmpl")):
        os.chdir("..")

    elif not os.path.exists("SummaryReport.tmpl"):
        raise "Could not find HTML template files."

    # Compile or load already precompiled template.
    template = TemplateManager().prepare("SummaryReport.tmpl")
    tproc = TemplateProcessor()

    # Set the title.
    mod = om.OpenModeller()
    tproc.set("om_version", mod.getVersion())
    tproc.set("om_num_algs", mod.numAvailableAlgorithms())

    # htmltmpl requires var name starting with uppercase (!?!)
    Entries = report_entry_set
    tproc.set("Entries", Entries)

    # get list of algorithms
    Algorithms = []
    algList = mod.availableAlgorithms()
    for i in range(0, len(algList)):
        alg = {}
        alg["class"] = "a"
        alg["id"] = algList[i].id
        alg["name"] = algList[i].name
        Algorithms.append(alg)

    tproc.set("Algorithms", Algorithms)

    # write the processed template to disk
    summary_file = file("index.html", "w")
    summary_file.write(tproc.process(template))
    summary_file.close()

    # Compile or load already precompiled template.
    template = TemplateManager().prepare("MapReport.tmpl")
    tproc = TemplateProcessor()

    # htmltmpl requires var name starting with uppercase (!?!)
    Mapstats = map_stats_entry_set
    tproc.set("Mapstats", Mapstats)

    # write the processed template to disk
    map_file = file("MapReport.html", "w")
    map_file.write(tproc.process(template))
    map_file.close()
Exemple #25
0
import honeyd
import time
import support
from htmltmpl import TemplateManager, TemplateProcessor

global counter

self.send_response(200)
self.send_header("Content-Type", "text/html")
self.send_nocache()
self.end_headers()

# Compile or load already precompiled template.
template = TemplateManager().prepare(self.root+"/templates/index.tmpl")
tproc = TemplateProcessor(0)

# Process commands given to us
message = support.parse_query(self.query)

# Set the title.
tproc.set("title", "Honeyd Administration Interface")

# Test
try:
    counter += 1
except:
    counter = 1

greeting = ("Welcome to the Honeyd Administration Interface."
            "You are visitor %d.<p>") % counter
Exemple #26
0
DB = "test"
USER = ""
PASSWD = ""
TABLE = """

    CREATE TABLE IF NOT EXISTS Products (
        id            INTEGER        NOT NULL AUTO_INCREMENT,
        name          VARCHAR(255)   NOT NULL,
        CONSTRAINT pkey_id
            PRIMARY KEY(id)
    )
    
"""

template = TemplateManager().prepare("products.tmpl")
tproc = TemplateProcessor()

# Assign a string to template variable named "title".
tproc.set("title", "Our products")

# Connect the database. Create the table.
db = MySQLdb.connect(db=DB,
                     user=USER,
                     passwd=PASSWD,
                     cursorclass=MySQLdb.cursors.DictCursor)
create_cur = db.cursor()
create_cur.execute(TABLE)
create_cur.close()

# Insert some data.
insert_cur = db.cursor()
Exemple #27
0
# 生成文档的title和最新更新时间列表
for file_path, category in article_category.items():
    fd = open(file_path)
    fd.seek(0)
    title = fd.readline()
    keyword = fd.readline()
    uuid = fd.readline()
    fd.close()
    article_title[file_path] = title
    article_keyword[file_path] = keyword
    article_uuid[file_path] = uuid
    article_lastmodify[file_path] = "%d" % os.stat(file_path).st_mtime

#============ 生成首页 =============#
template = TemplateManager().prepare(index_html_template)
tproc = TemplateProcessor(html_escape=0)

# Create the 'Menuitem' loop.
Menuitems = []
for category, cn_name in site_category.items():
    if category in article_category.values():
        menuitem = {}
        menuitem["menu_href"] = "/%s/index.html" % (category)
        menuitem["menu_name"] = cn_name
        Menuitems.append(menuitem)

# 首页显示最新的一篇文章内容
index_article = []
# create new article list
Newarticles = []
article_lastmodify_sort = sorted(article_lastmodify.items(),
Exemple #28
0
class Easydoc:
    """ Autogenerate documentation from docstrings.    

        This class provides all the functionality of easydoc. You can
        subclass it and override its processing methods module(),
        mclass() and method() to customize its behaviour.
        
        You also can easily use your own template to modify the output
        in any way you need. Output colors can be customized via
        parameters.
    """
    
    def __init__(self, template, debug=0):
        """ Constructor.             

            @header __init__(template, debug=0)
           
            @param template String containing template data.
            
            @param debug Enable or disable debugging messages.
            This optional parameter can be used to enable or disable debugging
            messages which are printed to stderr. By default debugging
            messages are disabled.
        """
        self._debug = debug
        self._classes = []
        self._functions = []
        self._class = {}        
        self._template = TemplateCompiler().compile_string(template)
        self._tproc = TemplateProcessor(html_escape=0)            
                    
    def process(self, module, bgcolor, textcolor, linkcolor, methodbg,
                with_hidden=0):
        """ Create documentation for a module.

            @header process(module, bgcolor, textcolor, linkcolor,
                            with_hidden=0)
            @return String containing the resulting HTML documentation.
            
            @param module Filename of the module to document.
            The module must be specified as filename. The module is not
            imported nor executed, only parsed.

            @param bgcolor Set background color.
            Accepts any valid CSS color value.

            @param textcolor Set text color.
            Accepts any valid CSS color value.

            @param linkcolor Set color of hyperlinks.
            Accepts any valid CSS color value.
            
            @param with_hidden Do not exclude hidden sections from output.
            This optional parameter can be used to force inclusion of
            hidden sections in the resulting documentation. Hidden sections
            are by default not included.            
        """
        mdict = {}
        self._tproc.set("bgcolor", bgcolor)
        self._tproc.set("textcolor", textcolor)
        self._tproc.set("linkcolor", linkcolor)
        self._tproc.set("methodbg", methodbg)

        # Parse the module.
        ast = parser.suite(open(module).read())
        module_info = easydocp.ModuleInfo(ast.totuple())
        self.module(module_info.get_docstring())

        # Class info.
        for mclass in module_info.get_class_names():
            class_info = module_info.get_class_info(mclass)            
            if self.mclass(mclass, class_info.get_docstring(), with_hidden):
                # The class should be included in the output.
                self._class["Methods"] = []
                for method in class_info.get_method_names():
                    method_info = class_info.get_method_info(method)
                    self.method(mclass, method, method_info.get_docstring(),
                                with_hidden)
                self.DEB("Finished class: " + mclass)
                self._classes.append(copy.copy(self._class))
            self._class.clear()                
        self._tproc.set("Classes", self._classes)

        # Functions info.
        for function in module_info.get_function_names():
            function_info = module_info.get_function_info(function)
            self.method("", function, function_info.get_docstring(),
                        with_hidden)
        self._tproc.set("Functions", self._functions)
        
        return self._tproc.process(self._template)

    ##############################################
    #              PRIVATE METHODS               #
    ##############################################

    def module(self, doc):
        """ Process docstring of a module. 
            @hidden
        """
        short, detailed, statements = self.parse(doc)
        self.DEB("Module: short: " + short)
        self.DEB("Module: statements: " + pprint.pformat(statements))

        self._tproc.set("short", short.strip())
        self._tproc.set("Detailed", self.detailed(detailed))

        # Statements.
        requires = []
        for statement in statements:
            param, data = statement
            if param == "name":
                self._tproc.set("name", data.strip())
                self.DEB("Module: name: " + data)
            elif param == "version":
                self._tproc.set("version", data.strip())
            elif param == "website":
                self._tproc.set("website", data.strip())
            elif param == "author-name":
                self._tproc.set("author-name", self.mangle(data))
            elif param == "author-email":
                self._tproc.set("author-email", data.strip())
            elif param == "license-name":
                self._tproc.set("license-name", data.strip())
            elif param == "license-url":
                self._tproc.set("license-url", data.strip())
            elif param == "require":
                requires.append( {"require": self.mangle(data)} )
            else:
                self.warn("Unknown statement: " + param)
        self._tproc.set("Requires", requires)
    
    def mclass(self, name, doc, with_hidden=0):
        """ Process docstring of a class.
            @hidden
        """
        short, detailed, statements = self.parse(doc)
        self.DEB("Class: " + name + ": short: " + short)
        self.DEB("Class: " + name + ": statements: " + \
                 pprint.pformat(statements))

        self._class["name"] = name
        self._class["short"] = short.strip()
        self._class["Detailed"] = self.detailed(detailed)

        for statement in statements:
            param, data = statement
            if param == "hidden":
                if not with_hidden:
                    self.DEB("Class: " + name + ": HIDDEN")
                    return 0
            else:
                self.warn("Unknown statement: " + param)
        else:
            return 1
            
    def method(self, mclass, name, doc, with_hidden=0):
        """ Process docstring of a method.
            @hidden
        """
        method = {}
        short, detailed, statements = self.parse(doc)
        if mclass:
            self.DEB("Method: " + name + ": short: " + short)
            self.DEB("Method: " + name + ": statements: " + \
                     pprint.pformat(statements))
        else:
            self.DEB("Function: " + name + ": short: " + short)
            self.DEB("Function: " + name + ": statements: " + \
                     pprint.pformat(statements))            

        method["name"] = name
        method["class"] = mclass
        method["short"] = short.strip()
        method["Detailed"] = self.detailed(detailed)

        parameters = []
        for statement in statements:
            param, data = statement
            if param == "hidden":
                if not with_hidden:
                    self.DEB("Method: " + name + ": HIDDEN")
                    return 0
            elif param == "header":
                header = data.strip()
                header = re.sub(r"\s+", " ", header)
                method["header"] = header
            elif param == "return":
                method["return"] = self.mangle(data)
            elif param == "param":
                parameter = {}

                # Split the data into first line and rest.
                lines = data.splitlines(KEEP_NEWLINES)
                first_line = lines[0].strip()
                
                # Split the first line into name and short description
                # of the parameter.
                fsplit = first_line.split(" ", 1)
                if len(fsplit) == 2:
                    pname, pshort = fsplit
                elif len(fsplit) == 1:
                    pname = fsplit[0]
                    pshort = ""
                else:
                    pname = ""
                    pshort = ""
                    
                if len(lines) > 1:
                    pdetailed = string.join(lines[1:])
                else:
                    pdetailed = ""

                self.DEB("Parameter: " + pname.strip())
                parameter["name"] = pname.strip()
                parameter["short"] = pshort.strip()
                parameter["Detailed"] = self.detailed(pdetailed)
                parameters.append(parameter)
            else:
                self.warn("Unknown statement: " + param)
        else:
            method["Parameters"] = parameters
            if mclass:
                self._class["Methods"].append(method)
            else:
                self._functions.append(method)
            return 1
                    
    def parse(self, doc):
        """ Parse a docstring.            
            
            Split the docstring into short description, detailed description
            and a list containing a tuple for every statement. The first
            element of the tuple is name of the statement, the second is the
            data of the statement.
            
            @hidden
        """            
        short = ""
        detailed = ""
        statements = []
        if not doc:
            return short, detailed, statements

        doc = doc.replace("\"\"\"", "")

        rc = re.compile(r"""
            ^\s*(@)([-\w]+)
        """, re.VERBOSE | re.MULTILINE)
        tokens = rc.split(doc)
        len_tokens = len(tokens)
        i = 0
        skip_param = 0
        while 1:
            if i == len_tokens:
                break
            if skip_param:
                skip_param = 0
                i += 2
                continue
            token = tokens[i]
            if token == "@":
                skip_param = 1
                param = tokens[i + 1]
                data = tokens[i + 2]
                statements.append((param, data))
            else:
                if not short:
                    lines = token.splitlines(KEEP_NEWLINES)
                    short = lines[0]
                    if len(lines) > 1:
                        detailed = string.join(lines[1:])
            i += 1
        return short, detailed, statements

    def DEB(self, str):
        """ Print debugging message to stderr if debugging is enabled.
            @hidden
        """
        if self._debug: print >> sys.stderr, str

    def warn(self, warning):
        """ Print a warning to stderr.
            @hidden
        """
        print >> sys.stderr, warning

    def mangle(self, str):
        """ Strip leading and trailing whitespace. Convert URL to hyperlink.
            @hidden
        """
        str = str.strip()
        return re.sub(r"\[ (http://.*?) \]",
                      r'<a href="\1">\1</a>', str)

    def detailed(self, str):
        """ Process detailed descritpion.
            
            Split it into paragraphs at empty lines.
            Return list of the paragraphs.
            
            @hidden
        """
        paragraphs = []
        rc = re.compile(r"^\s*$", re.MULTILINE)  # allow any whitespace
        for p in rc.split(str):
            if re.search(r"\S", p):
                paragraphs.append( {"paragraph": self.mangle(p)} )
        return paragraphs
Exemple #29
0
import time
import support
from htmltmpl import TemplateManager, TemplateProcessor

self.send_response(200)
self.send_header("Content-Type", "text/html")
self.send_nocache()
self.end_headers()

# Process commands given to us
message = support.parse_query(self.query)

# Compile or load already precompiled template.
template = TemplateManager().prepare(self.root + "/templates/index.tmpl")
tproc = TemplateProcessor(0)

# Set the title.
tproc.set("title", "Honeyd Configuration Interface")

content = "Welcome to the Honeyd Configuration Interface.<p>"
content += support.config_table()
content += "<p>"
content += support.config_ips(self.root)

if message:
    tproc.set("message", message)
tproc.set("content", content)
tproc.set("uptime", support.uptime())

# Print the processed template.
self.wfile.write(tproc.process(template))