Exemplo n.º 1
0
    def test_send_event(self):
        output = file.Output({'jsonpath': '/dev/null'})
        with unittest.mock.patch.object(output, '_outputfile') as fp:
            app = Bottle()
            app.config = {'elasticpot': {'nodeid': 'foo'}}
            default_app.push(app)
            request.bind({'bottle.app': app})
            try:
                output.send({
                    'timestamp': '',
                    'src_ip': '127.0.0.1',
                    'src_port': '11111',
                    'dest_ip': '127.0.10.1',
                    'dest_port': '22222',
                    'querystring': '/?pretty',
                    'body': '',
                    'raw': '',
                })
            finally:
                default_app.pop()
            assert fp.write.call_count == 1
            assert fp.write.call_args[0][0].endswith('\n')

            event = json.loads(fp.write.call_args[0][0])
            assert isinstance(event, dict)
            assert event['honeypot']['name'] == 'Elasticpot'
Exemplo n.º 2
0
    def test_send_event(self):
        output = ews.Output({
            'username': '******',
            'token': 'abcdefghijklmnop',
            'rhost_first': 'http://localhost'
        })
        with unittest.mock.patch('requests.post') as post:
            app = Bottle()
            app.config = {'elasticpot': {'nodeid': 'foo'}}
            default_app.push(app)
            request.bind({'bottle.app': app})

            try:
                output.send({
                    'timestamp': '1 January 1900',
                    'src_ip': '127.0.0.1',
                    'src_port': '11111',
                    'dest_ip': '127.0.10.1',
                    'dest_port': '22222',
                    'querystring': '/?pretty',
                    'body': '--PAYLOAD DATA HERE--',
                    'raw': '--BASE64 ENCODED STRING HERE--',
                })
            finally:
                default_app.pop()

            assert post.call_count == 1
            assert post.call_args[0][0] == 'http://localhost'
            assert post.call_args[1]['data'].strip() == EXPECTED.strip()
Exemplo n.º 3
0
    def test_send_event(self):
        output = console.Output({})
        with unittest.mock.patch('sys.stdout') as stdout:
            app = Bottle()
            app.config = {'elasticpot': {'nodeid': 'foo'}}
            default_app.push(app)
            request.bind({'bottle.app': app})
            try:
                output.send({
                    'timestamp': '',
                    'src_ip': '127.0.0.1',
                    'src_port': '11111',
                    'dest_ip': '127.0.10.1',
                    'dest_port': '22222',
                    'querystring': '/?pretty',
                    'body': '',
                    'raw': '',
                })
            finally:
                default_app.pop()
            '''assert stdout.write.call_count == 1'''
            assert stdout.write.call_args[0][0].endswith('\n')

            event = json.loads(stdout.write.call_args_list[0][0][0])
            assert isinstance(event, dict)
            assert event['src_ip'] == '127.0.0.1'
def get_app():
    """return bottle app that includes all sub-apps"""
    from bottle import default_app
    default_app.push()
    for module in ("apps.hosts", "apps.rs", "apps.sh"):
        __import__(module)
    app = default_app.pop()
    return app
Exemplo n.º 5
0
def get_app():
    """return bottle app that includes all sub-apps"""
    from bottle import default_app
    default_app.push()
    for module in ("mongo_orchestration.apps.servers",
                   "mongo_orchestration.apps.replica_sets",
                   "mongo_orchestration.apps.sharded_clusters"):
        __import__(module)
    app = default_app.pop()
    return app
Exemplo n.º 6
0
def get_app():
    """return bottle app that includes all sub-apps"""
    from bottle import default_app
    default_app.push()
    for module in ("mongo_orchestration.apps.servers",
                   "mongo_orchestration.apps.replica_sets",
                   "mongo_orchestration.apps.sharded_clusters"):
        __import__(module)
    app = default_app.pop()
    return app
Exemplo n.º 7
0
def import_plugins(path=None, pattern="*.py"):
    """
    Finds all python files in the plugins sub directory and its sub-directories and then import them as bottle app.
    If the module contains a global called 'mount_url' then the bottle app will be mounted on the specified url.

    :param path:     The directory (and its sub directories) that will be searched for plugins. Default: ./plugins
    :param pattern:  The file pattern that will be searched for a plugin (e.g. "*_plugin.py"). Default: *.py

    """
    root = dirname(realpath(__file__))  # root directory of this file
    path = path or join(root, "plugins")  # default plugins root directory
    plugins = default_app().config['server_plugins'] = []

    for fn in listdir(path):
        if isdir(fn):
            import_plugins(join(path, fn),
                           pattern)  # plugin sub directory, search here
        if fnmatch(fn, pattern):  # found a plugin
            module = fn[:-3]  # python module name (strip .py extenion and dir)
            url = None  # create a new Bottle app
            default_app.push(
            )  # install all routes during the import on a new default app
            try:
                sys.path.append(
                    path
                )  # temporarily add this path to the python system path
                m = import_module(
                    module)  # import the python module (strip .py extenion)
                url = getattr(
                    m, "mount_url",
                    f"/{module}/")  # fetch the url mount point for this plugin
                print(f"mounted: {module}")
            except ImportError as e:
                err_msg = "Could not import plugin module:" + fn + "\n" + str(
                    e)
                logger.exception(
                    err_msg)  # skip files that do not import properly
            finally:
                del sys.path[-1]  # clean up system path after the import
            plugin = default_app.pop(
            )  # pop the default app with the new routes
            if url and len(plugin.routes):
                if url == "/":
                    default_app().merge(
                        plugin)  # merge the plugin with the root app
                else:
                    default_app().mount(
                        url, plugin)  # mount the plugin onto the root app
                plugins.append({'module': module, 'url': url, 'app': plugin})
            else:
                plugins.append({'module': module, 'error': err_msg})
Exemplo n.º 8
0
    def __init__(self, name, catchall=True, autojson=True):
        super(Avalon, self).__init__(catchall, autojson)
        self.name = name
        self.blueprints = []
        self.router = Router()
        self._init_config(name)
        self._access_token = {}

        # 不知道为什么不能用add_hook
        self.add_hook('before_request', fill_session)
        self.add_hook('before_request', db_session_rollback)
        self.add_hook('after_request', save_session)

        default_app.push(self)
Exemplo n.º 9
0
def load_app(target):
    """ Load a bottle application from a module and make sure that the import
        does not affect the current default application, but returns a separate
        application object. See :func:`load` for the target parameter. """
    global NORUN;NORUN, nr_old = True, NORUN
    try:
        tmp = default_app.push()  # Create a new "default application"
        rv = load(target)  # Import the target module
        pdb.set_trace()
        return rv if callable(rv) else tmp
    finally:
        default_app.remove(tmp)  # Remove the temporary added default application
        NORUN = nr_old
Exemplo n.º 10
0
#!/usr/bin/python
from bottle import run,route,app,request,response,template,default_app,Bottle,debug,abort
import sys
import os
import platform
import subprocess
import re
#from flup.server.fcgi import WSGIServer
#from cStringIO import StringIO
#import memcache

app = Bottle()
default_app.push(app)

VERSION = "2.2"

platforms = platform.uname()[0]
print "Platform = %s" % platforms
if platforms == 'Windows':               # Windows
    PLATDIR = os.environ["ProgramFiles"]
    PLATDIR = '"' + PLATDIR + '"'
    print "AppInventor tools located here: %s" % PLATDIR
else:
    sys.exit(1)

@route('/ping/')
def ping():
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Headers'] = 'origin, content-type'
    response.headers['Content-Type'] = 'application/json'
    return '{ "status" : "OK", "version" : "%s" }' % VERSION
#!/usr/bin/python
from bottle import run, route, app, request, response, template, default_app, Bottle, debug, abort
import sys
import os
import platform
import subprocess
import re
#from flup.server.fcgi import WSGIServer
#from cStringIO import StringIO
#import memcache

app = Bottle()
default_app.push(app)

VERSION = "2.1"

platforms = platform.uname()[0]
print "Platform = %s" % platforms
if platforms == 'Windows':  # Windows
    PLATDIR = os.environ["ProgramFiles"]
    PLATDIR = '"' + PLATDIR + '"'
    print "AppInventor tools located here: %s" % PLATDIR
else:
    sys.exit(1)


@route('/ping/')
def ping():
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Headers'] = 'origin, content-type'
    response.headers['Content-Type'] = 'application/json'
Exemplo n.º 12
0
                utils.i10n_select(res["title"], langs),
                'level':
                res["level"],
                'update':
                str(res["timestamp"]),
                'usernames':
                list(
                    map(
                        lambda elem: "username" in elem and elem["username"] or
                        "", res['elems'] or [])),
                'osm_ids':
                dict(
                    map(
                        lambda k_g: [{
                            'N': 'nodes',
                            'W': 'ways',
                            'R': 'relations'
                        }[k_g[0]],
                                     list(map(lambda g: g['id'], k_g[1]))],
                        groupby(
                            sorted(res['elems'] or [],
                                   key=lambda e: e['type']),
                            lambda e: e['type']))),
            })
        out.append(i)

    return {'issues': out}


default_app.push(app_0_2)
Exemplo n.º 13
0
# web_config = config_dict.get('web', {})
# solr_config = config_dict.get('solr', {})
# email_config = config_dict.get('email', {})

# production = web_config.get('production') == 'True'
production = False
def process_routes(routes):
    for config in routes:
        route(config["url"], method=config["method"])(config["controller"])
    if production:
        error(404)(not_found)
        error(405)(not_allowed)
        # error(500)(handle_exception)


default_app.push()

# exception_handler = ExceptionsHandlerPlugin()
# bottle.install(exception_handler)

# solr = SolrPlugin(solr_config)
# bottle.install(solr)

process_routes(ROUTES)

application = default_app.pop()
application.catchall = False

if not production:
    bottle.debug(True)
Exemplo n.º 14
0
def new_app():
    return app_stack.push()
Exemplo n.º 15
0
# email_config = config_dict.get('email', {})

# production = web_config.get('production') == 'True'
production = False


def process_routes(routes):
    for config in routes:
        route(config["url"], method=config["method"])(config["controller"])
    if production:
        error(404)(not_found)
        error(405)(not_allowed)
        # error(500)(handle_exception)


default_app.push()

# exception_handler = ExceptionsHandlerPlugin()
# bottle.install(exception_handler)

# solr = SolrPlugin(solr_config)
# bottle.install(solr)

process_routes(ROUTES)

application = default_app.pop()
application.catchall = False

if not production:
    bottle.debug(True)