Esempio n. 1
0
def networkScanner():
    conf.verb = 0

    client_ip = netifaces.ifaddresses(conf.iface)[2][0]['addr']
    client_netmask = netifaces.ifaddresses(conf.iface)[2][0]['netmask']

    print "[!] Network scan process started for {0}".format(
        options.target_network)
    targetNetwork = ipaddress.IPv4Network(unicode(options.target_network),
                                          strict=False)
    counter = 0
    for machine in targetNetwork.hosts():
        sip = sip_packet.sip_packet("options",
                                    machine.exploded,
                                    options.dest_port,
                                    client_ip,
                                    protocol="socket",
                                    wait=True)
        result = sip.generate_packet()
        if result["status"]:
            if result["response"]['code'] == 200:
                utilities.writeFile(options.ip_list,
                                    '{0}\n'.format(machine.exploded))
                print "[+] New live IP found on {0}".format(machine.exploded)
                counter += 1
    print "[!] Network scan process finished and {0} live IP address(s) found.".format(
        str(counter))
Esempio n. 2
0
def generateModel(path,app,model,properties):
    """generates a specific model"""
    name = model
    print "Generating Model: " + name
    modelStr = "class %s(models.Model):\n" % name

    #process fields
    try:
        for key in iter(properties["fields"]):
            modelStr += generateModelField(key,properties["fields"][key])
    except KeyError:
        modelStr += "    pass"

 
    #register it in the admin panel right before returning it       
    writeFile(os.path.join(path,'admin.py'),\
              "\nfrom django.contrib import admin\nfrom models import %s\nadmin.site.register(%s)\n" % (name,name),\
              mode='a')

    #write the unicode function for admin display if nessisary
    try:
        remapped = tokenizer(properties["admin"],'self.')
        modelStr += "\n    def __unicode__(self):\n    "
        modelStr += "    return " + remapped + "\n"

    except KeyError:
        pass #no special instructions for rendering
    
    return modelStr + "\n"
Esempio n. 3
0
def test(network, inputs):
    confusion_matrix = defaultdict(Counter)
    pred_lst = []

    # for example in inputs.values():
    for key in inputs.keys():
        example = inputs[key]
        image_file = key.split('|')[0]
        true_orientation = example[1]
        x = example[0]

        propagator = propagate_forward(network, x, true_orientation)

        soft_max_vals = propagator.soft_max_vals
        predicted_orientation = get_orientation_value(
            soft_max_vals.index(max(soft_max_vals)))
        confusion_matrix[str(true_orientation)][str(
            predicted_orientation)] += 1
        pred = image_file + ' ' + str(predicted_orientation)
        pred_lst.append(pred)

    writeFile(pred_lst, 'nnet_output.txt')

    result = Result(confusion_matrix)
    return result
Esempio n. 4
0
def generateForms(path,app,properties):
    """Generates a form for each model for easy search/creation"""
    forms = "from django.utils.translation import gettext as _\n"
    forms += "from django.forms import ModelForm\n\n"

    for model in iter(properties):
        forms += generateForm(path,app,model,properties[model])
    
    #write to the forms file
    writeFile(os.path.join(path,'forms.py'), forms)
Esempio n. 5
0
def generateModels(path,app,properties):
    """Generates models for a given app"""

    print "Generating models for app: " + app
    models = "from django.contrib.auth.models import User\nfrom django.db import models\n\n"

    for model in iter(properties):
        models += generateModel(path, app, model, properties[model])
        
    #write the model
    writeFile(os.path.join(path,'models.py'), models)
Esempio n. 6
0
def handleSettings(settings_file, properties):
    """Reads the settings file and calls functions to edit it using properties
       Once this is done it writes any changes and closes the file"""

    #important basics might be editable later for now constant
    contents = "import os\n"
    contents += "BASE_DIR = os.path.dirname(os.path.abspath(__file__))\n\n"

    contents += "SITE_ID = 1\n"

    contents += "DEBUG = True\nTEMPLATE_DEBUG=DEBUG\n"  #different in different sub settings files

    contents += "ALLOWED_HOSTS = ['']\n\n"  #this needs to be changable

    contents += "ROOT_URLCONF = '%s.urls'\n" % properties['website']['name']

    contents += "STATIC_URL = '/static/'\n"

    contents += "WSGI_APPLICATION = '%s.wsgi.application'" % properties[
        'website']['name']  #this is only for testing env

    #middleware
    contents = handleMiddleware(contents, properties)

    #handle
    contents = handleContextProcessors(contents, properties)

    #generate secret key
    contents = generateSecretKey(contents)

    #add administrators
    contents = handleAdmins(contents, properties)
    contents += "MANAGERS = ADMINS\n"

    #add installed apps and south
    contents = handleApps(contents, properties)

    #add in template dirs at the end
    contents = handleTemplates(contents, properties)

    #add static dirs and root
    contents = handleStatic(contents, properties)

    #setup the database
    contents = handleDatabase(contents, properties)

    #rewite changes
    writeFile(settings_file, contents)

    #last thing is to delete the pyc of the settings file otherwise it will be out of date
    call(["rm", settings_file + "c"])
def handleSettings(settings_file, properties):
    """Reads the settings file and calls functions to edit it using properties
       Once this is done it writes any changes and closes the file"""

    #important basics might be editable later for now constant
    contents = "import os\n"
    contents += "BASE_DIR = os.path.dirname(os.path.abspath(__file__))\n\n"

    contents += "SITE_ID = 1\n"

    contents += "DEBUG = True\nTEMPLATE_DEBUG=DEBUG\n" #different in different sub settings files

    contents += "ALLOWED_HOSTS = ['']\n\n" #this needs to be changable

    contents += "ROOT_URLCONF = '%s.urls'\n" % properties['website']['name']

    contents += "STATIC_URL = '/static/'\n"

    contents += "WSGI_APPLICATION = '%s.wsgi.application'" % properties['website']['name'] #this is only for testing env

    #middleware
    contents = handleMiddleware(contents,properties)

    #handle 
    contents = handleContextProcessors(contents,properties)

    #generate secret key
    contents = generateSecretKey(contents)

    #add administrators
    contents = handleAdmins(contents,properties)
    contents += "MANAGERS = ADMINS\n"

    #add installed apps and south
    contents = handleApps(contents,properties)

    #add in template dirs at the end
    contents = handleTemplates(contents,properties)

    #add static dirs and root
    contents = handleStatic(contents,properties)

    #setup the database
    contents = handleDatabase(contents,properties)

    #rewite changes
    writeFile(settings_file,contents)

    #last thing is to delete the pyc of the settings file otherwise it will be out of date
    call(["rm", settings_file + "c"])
Esempio n. 8
0
def printResult(result, target):
    user_agent = ""
    for key, value in result["response"]['headers'].iteritems():
        if key == "user-agent":
            user_agent = list(value)[0]

    if utilities.defineTargetType(user_agent) == "Server":
        print "\033[1;32m[+] New live IP found on " + target + ", It seems as a SIP Server.\033[0m"
        utilities.writeFile(options.ip_list,
                            target + ";" + user_agent + ";SIP Server" + "\n")
    else:
        print "\033[1;32m[+] New live IP found on " + target + ", It seems as a SIP Client.\033[0m"
        utilities.writeFile(options.ip_list,
                            target + ";" + user_agent + ";SIP Client" + "\n")
Esempio n. 9
0
def createPages(properties):
    """Iterate through and create pages"""
    #location of main app is used a lot
    consts.MAIN = os.path.join(consts.PROJECT, 'main')

    #read standard.html file
    with open(os.path.join(consts.MAIN, 'templates', 'standard.html'),
              'r') as f:
        standard = f.read()

    #now splice in all the content for standard
    #add in the header

    standard = re.sub("{% block header %}",
                      "{%% block header %%}%s" % generateHeader(properties),
                      standard,
                      flags=re.DOTALL)

    #menu
    standard = re.sub("{% block menu %}",
                      "{%% block menu %%}%s" % generateMenu(properties),
                      standard,
                      flags=re.DOTALL)

    #footer
    standard = re.sub("{% block footer %}",
                      "{%% block footer %%}%s" % generateFooter(properties),
                      standard,
                      flags=re.DOTALL)

    #write the new standard.html
    with open(os.path.join(consts.MAIN, 'templates', 'standard.html'),
              'w') as f:
        f.write(standard)

#at the top of a view file
    viewHeader = """from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from django.template.loader import render_to_string
from middletier import permissionsCheck
from django.http import HttpResponse
from django.contrib import messages

"""
    writeFile(os.path.join(consts.MAIN, 'views.py'), viewHeader)

    for page in iter(properties["pages"]):
        generatePage("main", page, consts.MAIN, 'standard',
                     properties["pages"][page], True)
Esempio n. 10
0
def writeURLS(properties):
    """Writes the urls file, last thing done in the setup process to make sure there are no stray urls to be added"""
    urlfile = """from django.conf.urls import include, patterns, url

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls)),
"""

    for url in globs.URLS:
        urlfile += tabify(url+",",1)

    urlfile += ")\n"
        
    writeFile(os.path.join(consts.PROJECT,properties['website']['name'],'urls.py'),urlfile)
Esempio n. 11
0
def networkScanner():
    conf.verb = 0
    
    client_ip = netifaces.ifaddresses(conf.iface)[2][0]['addr']
    client_netmask = netifaces.ifaddresses(conf.iface)[2][0]['netmask']
    
    print "[!] Network scan process started for {0}".format(options.target_network)
    targetNetwork = ipaddress.IPv4Network(unicode(options.target_network), strict=False)
    counter = 0
    for machine in targetNetwork.hosts():
        sip = sip_packet.sip_packet("options", machine.exploded, options.dest_port, client_ip, protocol="socket", wait=True)
        result = sip.generate_packet()
        if result["status"]: 
            if result["response"]['code'] == 200:
                utilities.writeFile(options.ip_list, '{0}\n'.format(machine.exploded))
                print "[+] New live IP found on {0}".format(machine.exploded)
                counter += 1
    print "[!] Network scan process finished and {0} live IP address(s) found.".format(str(counter))
Esempio n. 12
0
def networkScanner():
    conf.verb = 0
    os.system("toilet SIP-NES")
    
    client_ip = netifaces.ifaddresses(conf.iface)[2][0]['addr']
    client_netmask = netifaces.ifaddresses(conf.iface)[2][0]['netmask']
    
    print "[!] Network scan process started for {0}".format(options.target_network)
    targetNetwork = ipaddress.IPv4Network(unicode(options.target_network), strict=False)
    counter = 0
    for machine in targetNetwork.hosts():
        sip = SipPacket("options", machine.network_address, options.dest_port, client_ip, protocol="tcp", wait=True)
        result = sip.generate_packet()
        if result["response"] and result["response"][code] == 200:
            utilities.writeFile(options.ip_list, '{0}\n'.format(machine.network_address))
            print "[+] New live IP found on {0}".format(machine.network_address)
            counter++
    print "[!] Network scan process finished and {0} live IP address(s) found.".format(str(counter))
Esempio n. 13
0
def writeURLS(properties):
    """Writes the urls file, last thing done in the setup process to make sure there are no stray urls to be added"""
    urlfile = """from django.conf.urls import include, patterns, url

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls)),
"""

    for url in globs.URLS:
        urlfile += tabify(url + ",", 1)

    urlfile += ")\n"

    writeFile(
        os.path.join(consts.PROJECT, properties['website']['name'], 'urls.py'),
        urlfile)
Esempio n. 14
0
def createPages(properties):
    """Iterate through and create pages"""
    #location of main app is used a lot
    consts.MAIN = os.path.join(consts.PROJECT, 'main')

    #read standard.html file
    with open(os.path.join(consts.MAIN,'templates', 'standard.html'), 'r') as f:
        standard = f.read()

    #now splice in all the content for standard
    #add in the header

    standard = re.sub("{% block header %}", "{%% block header %%}%s"%generateHeader(properties),standard,flags=re.DOTALL)

    #menu
    standard = re.sub("{% block menu %}", "{%% block menu %%}%s"%generateMenu(properties),standard,flags=re.DOTALL)

    #footer
    standard = re.sub("{% block footer %}", "{%% block footer %%}%s"%generateFooter(properties),standard,flags=re.DOTALL)

    #write the new standard.html
    with open(os.path.join(consts.MAIN, 'templates', 'standard.html'), 'w') as f:
        f.write(standard)    

#at the top of a view file
    viewHeader = """from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from django.template.loader import render_to_string
from middletier import permissionsCheck
from django.http import HttpResponse
from django.contrib import messages

"""
    writeFile(os.path.join(consts.MAIN, 'views.py'), viewHeader)

    for page in iter(properties["pages"]):
        generatePage("main", page, consts.MAIN, 'standard', properties["pages"][page], True)
Esempio n. 15
0
def generatePage(app, name, appPath, parent, properties, top):
    """
    Generate a page given a dict of properties
    
    A page consists of both a view and a template both are generated by this function.
    """

    print "Generating page: " + name

    #basics for each page template
    tabs = 0
    page = "<!-- Generated code for page: " + name + " -->\n" 
    page += tabify("{%% extends \"%s.html\" %%}" % parent, tabs)

    
    #Generate unique portion for each page
    try:
        page += tabify(("{%% block title %%}%s{%% endblock %%}" % properties["title"]), tabs)
    except KeyError:
        pass #no title for page


    #if this is a top level page fill in the content block
    if top:
        try:
            page += "{% block content %}" + handlePercentToken(properties["template"],'{{ ','|safe }}') + "{% endblock %}"
        except KeyError:
            print "Page " + name + " has no content"
    else:#otherwise we just pop everything in assuming the percent tokens are set up right
        try:
            page += handlePercentToken(properties["template"],'{{ ','|safe }}')
        except KeyError:
            print "page " + name + " has no content"

    with open(os.path.join(appPath, 'templates', name+'.html'), 'w') as f:
        f.write(page)
        
    tabs = 0
    #write view
    #urls need to count capture groups
    args = "request"

    try:
        counter = 1
        for symbol in properties["url"]:
            if symbol == "(": #assume matching for now
                args += ",u_" + str(counter)
                counter += 1
    except KeyError:
        pass #didnt have a url
    
    view = ""
    
    #now the definition of the view function
    view += tabify("def %s(%s):" % (name, args), tabs)
    tabs += 1

    #time to call the access function
    try:
        login = properties['access']['login'] #requires a login
    except KeyError:
        login = "******"

    try:
        groups = properties['access']['groups'] #get groups required
    except KeyError:
        groups = ""


    try:
        error_message = "messages.add_message(request, messages.ERROR, '%s')" % properties['access']['failmessage']
    except KeyError:
        error_message = "messages.add_message(request, messages.ERROR, 'Something went wrong man!')"

    try:
        redirect = "return %s(request)" % properties['access']['fail']
    except KeyError:
        redirect = "return HttpResponse('Denied', status=403)"

    view += tabify("if not permissionsCheck(request,%s,'%s'):" % (login,groups), tabs)
    tabs += 1
    view += tabify(error_message, tabs)
    view += tabify(redirect, tabs)
    tabs -= 1

    #time to define variables in the page
    view += tabify("d = {}",tabs) #to hold the variables
    for key in iter(properties):
        if key not in ["title", "url", "template", "pages", "access"]: #predefined keys, anything else is a variable
            view += decodePageKey(key,properties[key],tabs)

    view += tabify("return render(request,\"%s.html\",d)" % name, tabs)
    
    #write the view files
    writeFile(os.path.join(appPath, 'views.py'), view, 'a')

    
    #adds a url mapping
    try:
        addURL(properties['url'],"%s.views.%s" % (app, name), name)
    except KeyError:
        pass #wasnt a leaf page, dont really care if its missing a url

    #generate all sub pages
    try:
        for key in iter(properties['pages']):
            generatePage(app, key, appPath, name, properties['pages'][key], False)
    except KeyError:
        pass #this was a leaf page
import utilities, functions

kmers = utilities.readFile('stepik\dataset_200_8.txt')


def de_bruijn_kmers(kmers):
    graph = {}
    for kmer in kmers:
        prefix = kmer[0:-1]
        suffix = kmer[1:]
        functions.insert(graph, prefix, suffix)

    output = ''
    keys = list(graph.keys())
    keys.sort()
    for key in keys:
        l = ','.join(graph[key])
        output += key + ' -> ' + l + '\n'
    return output


#print(de_bruijn_kmers(kmers))

utilities.writeFile('stepik\output.txt', de_bruijn_kmers(kmers))
Esempio n. 17
0
def configureApp(path, app, properties):
    """After it has been created it is populated"""
    print "Configuring app: " + app


    #where to put template chains
    templates = os.path.join(path, 'templates')

    #generate themes
    theme = path + "/static/"
    print "Generating: " + theme
    try:
        call(["mkdir", theme])
        call(["mkdir", templates])
        if call(["cp","-a", os.path.join(consts.RESOURCES, 'themes', properties['theme'],'static','.'), theme]) == 1:
            if call(["cp", "-a", os.path.join(consts.PATH, properties['theme'], 'static',  '.'), theme]) == 1:
                print "Failed to find theme: " + properties['theme'] + " static files"
                sys.exit(1)
        if call(["cp", "-a", os.path.join(consts.RESOURCES, 'themes', properties['theme'], 'templates', '.'), templates]) == 1:
            if call(["cp", "-a", os.path.join(consts.PATH, properties['theme'], 'templates',  '.'), templates]) == 1:
                print "Failed to find theme " + properties['theme'] + " templates"

        call(["cp", "-a", os.path.join(consts.RESOURCES, 'themes', 'core', '.'), theme])
        call(["cp", "-a", os.path.join(consts.RESOURCES, 'templatechains', 'core','.'), templates])
    except:
        print "Failed to generate theme"
    
    #generate the models
    try:
        generateModels(path,app,properties['models'])

        #when done writing models for this app migrate it
        #call([consts.PYTHON, consts.MANAGE, "schemamigration", app, "--intial"])

        #generate default html for displaying the models, these are not fullon pages rather
        #they are small snipets that can be loaded by other pages by using a view to access them
        generateModelView(path,app,properties['models'])
        
        #generate middletier functions for each model
        generateMiddletier(path,app,properties['models'])
        
        #generate the form generators
        generateForms(path,app,properties['models'])
        
    except KeyError:
        #but we still want to make a models file
        writeFile(os.path.join(path,'models.py'), "from django.contrib.auth.models import User")
        print app + " has no models"

    if app == 'main':
        #set urls to callback to the middletier
        addURL('api/login/', 'main.middletier.login', 'login')
        addURL('api/logout/', 'main.middletier.logout', 'logout')
        addURL('api/signup/', 'main.middletier.signup', 'signup')

        #need to put in the context processor that allows us to access login/logout/signout stuff
        call(["cp", os.path.join(consts.RESOURCES,'processors','context_processors.py'),os.path.join(consts.PROJECT,'main','context_processors.py')])
        #copy in the middletier
        call(["cp", os.path.join(consts.RESOURCES,'middletier','middletier.py'),os.path.join(consts.PROJECT,'main','middletier.py')])
        #copy in the form data
        call(["cp", os.path.join(consts.RESOURCES,'userforms.html'),os.path.join(consts.PROJECT,'main','templates','userforms.html')])
Esempio n. 18
0
def generatePage(app, name, appPath, parent, properties, top):
    """
    Generate a page given a dict of properties
    
    A page consists of both a view and a template both are generated by this function.
    """

    print "Generating page: " + name

    #basics for each page template
    tabs = 0
    page = "<!-- Generated code for page: " + name + " -->\n"
    page += tabify("{%% extends \"%s.html\" %%}" % parent, tabs)

    #Generate unique portion for each page
    try:
        page += tabify(
            ("{%% block title %%}%s{%% endblock %%}" % properties["title"]),
            tabs)
    except KeyError:
        pass  #no title for page

    #if this is a top level page fill in the content block
    if top:
        try:
            page += "{% block content %}" + handlePercentToken(
                properties["template"], '{{ ', '|safe }}') + "{% endblock %}"
        except KeyError:
            print "Page " + name + " has no content"
    else:  #otherwise we just pop everything in assuming the percent tokens are set up right
        try:
            page += handlePercentToken(properties["template"], '{{ ',
                                       '|safe }}')
        except KeyError:
            print "page " + name + " has no content"

    with open(os.path.join(appPath, 'templates', name + '.html'), 'w') as f:
        f.write(page)

    tabs = 0
    #write view
    #urls need to count capture groups
    args = "request"

    try:
        counter = 1
        for symbol in properties["url"]:
            if symbol == "(":  #assume matching for now
                args += ",u_" + str(counter)
                counter += 1
    except KeyError:
        pass  #didnt have a url

    view = ""

    #now the definition of the view function
    view += tabify("def %s(%s):" % (name, args), tabs)
    tabs += 1

    #time to call the access function
    try:
        login = properties['access']['login']  #requires a login
    except KeyError:
        login = "******"

    try:
        groups = properties['access']['groups']  #get groups required
    except KeyError:
        groups = ""

    try:
        error_message = "messages.add_message(request, messages.ERROR, '%s')" % properties[
            'access']['failmessage']
    except KeyError:
        error_message = "messages.add_message(request, messages.ERROR, 'Something went wrong man!')"

    try:
        redirect = "return %s(request)" % properties['access']['fail']
    except KeyError:
        redirect = "return HttpResponse('Denied', status=403)"

    view += tabify(
        "if not permissionsCheck(request,%s,'%s'):" % (login, groups), tabs)
    tabs += 1
    view += tabify(error_message, tabs)
    view += tabify(redirect, tabs)
    tabs -= 1

    #time to define variables in the page
    view += tabify("d = {}", tabs)  #to hold the variables
    for key in iter(properties):
        if key not in ["title", "url", "template", "pages", "access"
                       ]:  #predefined keys, anything else is a variable
            view += decodePageKey(key, properties[key], tabs)

    view += tabify("return render(request,\"%s.html\",d)" % name, tabs)

    #write the view files
    writeFile(os.path.join(appPath, 'views.py'), view, 'a')

    #adds a url mapping
    try:
        addURL(properties['url'], "%s.views.%s" % (app, name), name)
    except KeyError:
        pass  #wasnt a leaf page, dont really care if its missing a url

    #generate all sub pages
    try:
        for key in iter(properties['pages']):
            generatePage(app, key, appPath, name, properties['pages'][key],
                         False)
    except KeyError:
        pass  #this was a leaf page