python Wvs的分析器(Web漏洞扫描程序)导出了xml结果。

Wvs的分析器(Web漏洞扫描程序)导出了xml结果。

wvs_parser.py
#!/usr/bin/env python
#-*- coding: utf-8 -*-

import bs4
import sys
import logging

logger = logging.getLogger(__file__)


class ParseException(Exception):
    def __init__(self, msg='???'):
        self.msg = msg

    def __str__(self):
        return "<ParseException: %s>" % self.msg


class WVSResult(object):

    def __init__(self, xml):
        try:
            self.soup = bs4.BeautifulSoup(xml, "xml")
        except:
            raise ParseException('Failed to parse xml with bs4')
        scan_tag = self.soup.Scan
        self.start_url = scan_tag.StartURL.string
        self.start_time = scan_tag.StartTime.string
        self.finish_time = scan_tag.FinishTime.string
        self.scan_time = scan_tag.ScanTime.string
        self._reports = []
        self._site_files = []

    @property
    def reports(self):
        report_items = self.soup.find_all('ReportItem')
        for r in report_items:
            id = r.get('id')
            name = r.Name.string
            details = r.Details.string
            affects = r.Affects.string
            parameter = r.Parameter.string
            severity = r.Severity.string
            type = r.Type.string
            impact = r.Impact.string
            description = r.Description.string
            detailed_information = r.DetailedInformation.string
            recommendation = r.Recommendation.string
            technical_details = {'request': r.TechnicalDetails.Request.string,
                                 'response': r.TechnicalDetails.Response.string
                                 }

            report_item = ReportItem(id, name, details, affects, parameter,
                                     severity, type, impact, description,
                                     detailed_information, recommendation,
                                     technical_details)
            self._reports.append(report_item)
        return self._reports

    @property
    def site_files(self):
        site_files = self.soup.find_all('SiteFile')
        for s in site_files:
            id = s.get('id')
            url = s.FullURL.string
            variation_urls = {}
            for variation in s.Variations.find_all('Variation'):
                variation_url = variation.URL.string
                if variation_url is None or not bool(variation_url.strip()):
                    continue
                url_key = hash(variation_url)
                if url_key not in variation_urls:
                    variation_urls[url_key] = variation_url
            site_file = SiteFile(id, url, variation_urls.values())
            self._site_files.append(site_file)
        return self._site_files


class SiteFile(object):
    def __init__(self, id, url, variation_urls):
        self.id = id
        self.url = url
        self.variation_urls = variation_urls

    def __str__(self):
        return '<SiteFile %s (%s)>' % (self.id, self.url)


class ReportItem(object):
    def __init__(self, id, name, details, affects, parameter, severity, type,
                 impact, description, detailed_information, recommendation,
                 technical_details):
        self.id = id
        self.name = name
        self.details = details
        self.affects = affects
        self.parameter = parameter
        self.severity = severity
        self.type = type
        self.impact = impact
        self.description = description
        self.detailed_information = detailed_information
        self.recommendation = recommendation
        self.technical_details = technical_details

    def __str__(self):
        return "<ReportItem %s (%s)>" % (self.id, self.name)


class Request(object):
    def __init__(self, req_str):
        self.req_str = req_str


class Response(object):
    def __init__(self, res_str):
        self.res_str = res_str


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

if __name__ == '__main__':
    logging.basicConfig(
        level=logging.DEBUG if '-v' in sys.argv else logging.WARN,
        format='%(asctime)s [%(levelname)s] %(message)s',
        datafmt='%Y-%m-%d %H-%M-%S')

    with open('export.xml') as f:
        xml = f.read()
    try:
        wvs_result = WVSResult(xml)
    except ParseException as e:
        logging.info(e.msg)
    except:
        logging.info("Wrong xml format of wvs's result")

    # count = 0
    # for r in wvs_result.reports:
        # print r.id
        # print r.name
        # print r.details
        # print r.affects
        # print r.parameter
        # print r.severity
        # print r.type
        # print r.impact
        # print r.description
        # print r.detailed_information
        # print r.recommendation
        # print r.technical_details
        # count += 1
        # if count == 3:
            # break
    # count = 0
    # for s in wvs_result.site_files:
        # print s.id
        # print s.url
        # for url in s.variation_urls:
            # print url
        # count += 1
        # if count == 3:
            # break

python 象限在PyClaw中测试

象限在PyClaw中测试

quadrants.py
#!/usr/bin/env python
# encoding: utf-8

"""
Solve the Euler equations of compressible fluid dynamics.
"""
from clawpack import pyclaw
from clawpack import riemann

solver = pyclaw.ClawSolver2D(riemann.rp2_euler_4wave)
solver.all_bcs = pyclaw.BC.extrap

domain = pyclaw.Domain([0.,0.],[1.,1.],[512,512])
solution = pyclaw.Solution(solver.num_eqn,domain)
gamma = 1.4
solution.problem_data['gamma']  = gamma
solver.dimensional_split = False
solver.transverse_waves = 2

# Set initial data
xx,yy = domain.grid.p_centers
l = xx<0.8; r = xx>=0.8; b = yy<0.8; t = yy>=0.8
solution.q[0,...] = 1.5*r*t + 0.532258064516129*l*t + 0.137992831541219*l*b + 0.532258064516129*r*b
u = 0.*r*t + 1.206045378311055*l*t + 1.206045378311055*l*b + 0.*r*b
v = 0.*r*t + 0.*l*t + 1.206045378311055*l*b + 1.206045378311055*r*b
p = 1.5*r*t + 0.3*l*t + 0.029032258064516*l*b + 0.3*r*b
solution.q[1,...] = solution.q[0,...] * u
solution.q[2,...] = solution.q[0,...] * v
solution.q[3,...] = 0.5*solution.q[0,...]*(u**2+v**2) + p/(gamma-1.)

#solver.evolve_to_time(solution,tend=0.3)
claw = pyclaw.Controller()
claw.tfinal = 0.8
claw.solution = solution
claw.solver = solver

status = claw.run()

python invert_a_matrix.py

invert_a_matrix.py
from copy import deepcopy
def invert(X):
    """
    Invert a matrix X according to gauss-jordan elimination
    In gauss-jordan elimination, we perform basic row operations to turn a matrix into
    row-echelon form.  If we concatenate an identity matrix to our input
    matrix during this process, we will turn the identity matrix into our inverse.
    X - input list of lists where each list is a matrix row
    output - inverse of X
    """
    #copy X to avoid altering input
    X = deepcopy(X)

    #Get dimensions of X
    rows = len(X)
    cols = len(X[0])

    #Get the identity matrix and append it to the right of X
    #This is done because our row operations will make the identity into the inverse
    identity = make_identity(rows,cols)
    for i in xrange(0,rows):
        X[i]+=identity[i]

    i = 0
    for j in xrange(0,cols):
        print("On col {0} and row {1}".format(j,i))
        #Check to see if there are any nonzero values below the current row in the current column
        zero_sum, first_non_zero = check_for_all_zeros(X,i,j)
        #If everything is zero, increment the columns
        if zero_sum==0:
            if j==cols:
                return X
            raise Exception("Matrix is singular.")
        #If X[i][j] is 0, and there is a nonzero value below it, swap the two rows
        if first_non_zero != i:
            X = swap_row(X,i,first_non_zero)
        #Divide X[i] by X[i][j] to make X[i][j] equal 1
        X[i] = [m/X[i][j] for m in X[i]]

        #Rescale all other rows to make their values 0 below X[i][j]
        for q in xrange(0,rows):
            if q!=i:
                scaled_row = [X[q][j] * m for m in X[i]]
                X[q]= [X[q][m] - scaled_row[m] for m in xrange(0,len(scaled_row))]
        #If either of these is true, we have iterated through the matrix, and are done
        if i==rows or j==cols:
            break
        i+=1

    #Get just the right hand matrix, which is now our inverse
    for i in xrange(0,rows):
        X[i] = X[i][cols:len(X[i])]

    return X

def check_for_all_zeros(X,i,j):
    """
    Check matrix X to see if only zeros exist at or below row i in column j
    X - a list of lists
    i - row index
    j - column index
    returns -
        zero_sum - the count of non zero entries
        first_non_zero - index of the first non value
    """
    non_zeros = []
    first_non_zero = -1
    for m in xrange(i,len(X)):
        non_zero = X[m][j]!=0
        non_zeros.append(non_zero)
        if first_non_zero==-1 and non_zero:
            first_non_zero = m
    zero_sum = sum(non_zeros)
    return zero_sum, first_non_zero

def swap_row(X,i,p):
    """
    Swap row i and row p in a list of lists
    X - list of lists
    i - row index
    p - row index
    returns- modified matrix
    """
    X[p], X[i] = X[i], X[p]
    return X

def make_identity(r,c):
    """
    Make an identity matrix with dimensions rxc
    r - number of rows
    c - number of columns
    returns - list of lists corresponding to  the identity matrix
    """
    identity = []
    for i in xrange(0,r):
        row = []
        for j in xrange(0,c):
            elem = 0
            if i==j:
                elem = 1
            row.append(elem)
        identity.append(row)
    return identity

python generateStringFromEnum.py

generateStringFromEnum.py
#!/usr/bin/python
__author__ = 'ant'

"""
Generate a C-function to convert an enum value into an NSString, and put it on the clipboard
Note, only handles NS_ENUM style enums at the moment.
"""

import sys
import re
import AppKit
import Foundation

from string import Template

indent = "    "

def pbcopy(s):
    board = AppKit.NSPasteboard.generalPasteboard()
    board.declareTypes_owner_([AppKit.NSStringPboardType], None)
    newStr = Foundation.NSString.stringWithString_(s)
    newData = \
        newStr.nsstring().dataUsingEncoding_(Foundation.NSUTF8StringEncoding)
    board.setData_forType_(newData, AppKit.NSStringPboardType)


# Normailse stdin input: remove all newlines, condense contiguous whitespace to single space
# TODO: strip block comments while reading file
body = ' '.join([ line.rstrip("\n") for line in sys.stdin.readlines() ] )
# Strip c-style comments
body = re.sub(r'/\*.*?\*/',
              r' ',
              body)
body = re.sub(r'\s+',
              r' ',
              body)

# Process file
# ============

enumName = None

# NS_ENUM
# -------
enumMatch = re.search(r'NS_ENUM\s?\(\s?\w+\s?,\s?(\w+)\s?\)\s?\{([ A-z0-9_,]*)\}',body)

if enumMatch:
    enumName = enumMatch.group(1)
    enumMembers = enumMatch.group(2).replace(' ','').split(',')


if enumName:
    output = "NSString* stringFrom{enumName}({enumName} value)\n{{".format( enumName = enumName[0].upper() + enumName[1:] )
    output += "\n{indent}switch (value) {{".format(indent=indent)

    template = Template(r'{indent}case $member: return @"$member"; break;'.format(indent = indent))
    for member in enumMembers:
        output += "\n" + template.substitute(member = member)

    output += '\n{indent}default: return @"ERROR: Unknown {enumName} value."; break;'.format(indent=indent, enumName=enumName)
    output += '\n{indent}}}'.format(indent=indent)
    output += '\n}\n'

    pbcopy(output)

python 3D声学问题设置与Clawpack 4.3进行比较。

3D声学问题设置与Clawpack 4.3进行比较。

acoustics_3d.py
#!/usr/bin/env python
# encoding: utf-8

import numpy as np

def acoustics3D(iplot=False,htmlplot=False,use_petsc=False,outdir='./_output',solver_type='classic',disable_output=False,**kwargs):
    """
    Example python script for solving the 3d acoustics equations.
    """

    if use_petsc:
        import clawpack.petclaw as pyclaw
    else:
        from clawpack import pyclaw

    if solver_type=='classic':
        solver=pyclaw.ClawSolver3D()
        solver.cfl_max = 1.0
        solver.cfl_desired = 0.9
    else:
        raise Exception('Unrecognized solver_type.')

    from clawpack import riemann
    solver.rp = riemann.rp3_vc_acoustics
    solver.num_waves = 2
    solver.limiters = pyclaw.limiters.tvd.MC

    solver.bc_lower[0]=pyclaw.BC.periodic
    solver.bc_upper[0]=pyclaw.BC.periodic
    solver.bc_lower[1]=pyclaw.BC.periodic
    solver.bc_upper[1]=pyclaw.BC.periodic
    solver.bc_lower[2]=pyclaw.BC.periodic
    solver.bc_upper[2]=pyclaw.BC.periodic

    solver.aux_bc_lower[0]=pyclaw.BC.periodic
    solver.aux_bc_upper[0]=pyclaw.BC.periodic
    solver.aux_bc_lower[1]=pyclaw.BC.periodic
    solver.aux_bc_upper[1]=pyclaw.BC.periodic
    solver.aux_bc_lower[2]=pyclaw.BC.periodic
    solver.aux_bc_upper[2]=pyclaw.BC.periodic

    app = None
    if 'test' in kwargs:
        test = kwargs['test']
        if test == 'homogeneous':
            app = 'test_homogeneous'
        elif test == 'heterogeneous':
            app = 'test_heterogeneous'
        else: raise Exception('Unrecognized test')

    if app == 'test_homogeneous':
        solver.dimensional_split=False
        solver.transverse_waves = 2
        mx=60; my=60; mz=60
        zr = 1.0  # Impedance in right half
        cr = 1.0  # Sound speed in right half

    if app == 'test_heterogeneous' or app == None:
        solver.dimensional_split=False
        solver.dimensional_split=False
        solver.bc_lower[0]    =pyclaw.BC.wall
        solver.bc_lower[1]    =pyclaw.BC.wall
        solver.bc_lower[2]    =pyclaw.BC.wall
        solver.aux_bc_lower[0]=pyclaw.BC.wall
        solver.aux_bc_lower[1]=pyclaw.BC.wall
        solver.aux_bc_lower[2]=pyclaw.BC.wall
        mx=60; my=60; mz=60
        zr = 2.0  # Impedance in right half
        cr = 2.0  # Sound speed in right half

    solver.limiters = pyclaw.limiters.tvd.MC

    # Initialize domain
    x = pyclaw.Dimension('x',-1.0,1.0,mx)
    y = pyclaw.Dimension('y',-1.0,1.0,my)
    z = pyclaw.Dimension('z',-1.0,1.0,mz)
    domain = pyclaw.Domain([x,y,z])

    num_eqn = 4
    num_aux = 2 # density, sound speed
    state = pyclaw.State(domain,num_eqn,num_aux)

    zl = 1.0  # Impedance in left half
    cl = 1.0  # Sound speed in left half

    grid = state.grid
    grid.compute_c_centers()
    X,Y,Z = grid._c_centers

    state.aux[0,:,:,:] = zl*(X<0.) + zr*(X>=0.) # Impedance
    state.aux[1,:,:,:] = cl*(X<0.) + cr*(X>=0.) # Sound speed

    x0 = -0.5; y0 = 0.; z0 = 0.
    if app == 'test_homogeneous':
        r = np.sqrt((X-x0)**2)
        width=0.2
        state.q[0,:,:,:] = (np.abs(r)<=width)*(1.+np.cos(np.pi*(r)/width))

    elif app == 'test_heterogeneous' or app == None:
        r = np.sqrt((X-x0)**2 + (Y-y0)**2 + (Z-z0)**2)
        width=0.1
        state.q[0,:,:,:] = (np.abs(r-0.3)<=width)*(1.+np.cos(np.pi*(r-0.3)/width))

    else: raise Exception('Unexpected application')
        
    state.q[1,:,:,:] = 0.
    state.q[2,:,:,:] = 0.
    state.q[3,:,:,:] = 0.

    claw = pyclaw.Controller()
    claw.keep_copy = True
    if disable_output:
       claw.output_format = None
    claw.solution = pyclaw.Solution(state,domain)
    claw.solver = solver
    claw.outdir=outdir
    claw.num_output_times = 6

    # Solve
    claw.tfinal = 1.2
    status = claw.run()

    if htmlplot:  pyclaw.plot.html_plot(outdir=outdir,file_format=claw.output_format)
    if iplot:     pyclaw.plot.interactive_plot(outdir=outdir,file_format=claw.output_format)

    pinitial=claw.frames[0].state.get_q_global()
    pmiddle  =claw.frames[3].state.get_q_global()
    pfinal  =claw.frames[claw.num_output_times].state.get_q_global()

    if pinitial != None and pmiddle != None and pfinal != None:
        pinitial =pinitial[0,:,:,:].reshape(-1)
        pmiddle  =pmiddle[0,:,:,:].reshape(-1)
        pfinal   =pfinal[0,:,:,:].reshape(-1)
        final_difference =np.prod(grid.delta)*np.linalg.norm(pfinal-pinitial,ord=1)
        middle_difference=np.prod(grid.delta)*np.linalg.norm(pmiddle-pinitial,ord=1)

        if app == None:
            print 'Final error: ', final_difference
            print 'Middle error: ', middle_difference

        #import matplotlib.pyplot as plt
        #for i in range(claw.num_output_times):
        #    plt.pcolor(claw.frames[i].state.q[0,:,:,mz/2])
        #    plt.figure()
        #plt.show()

        return pfinal, final_difference

    else:
        
        return

if __name__=="__main__":
    import sys
    from clawpack.pyclaw.util import run_app_from_main
    output = run_app_from_main(acoustics3D)