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()
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 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'
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
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
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})
def make(): app = default_app.pop() app.catchall = False def error_catcher(environ, start_response): try: return app.wsgi(environ, start_response) except PermissionDenied: start_response('403 Permission denied', {}) return [json.dumps({'status': 'PermissionDenied'}).encode()] except ObjectDoesNotExist as err: error = DoesNotExist_to_str(err) start_response('404 %s' % error, {}) # or 200? return [json.dumps({'status': error}).encode()] return error_catcher
from bottle import route, default_app, request, static_file, hook, redirect from helpers import template, msg, addMenu from user import getUser import os pathToModule = os.path.dirname(__file__) import user import group import lecture import assigment import template as templateWeb # abychom se vyhnuli kolizi s helper fnc @route('/static/<filename:path>') def send_static(filename): return static_file(filename, root=pathToModule + "/static/") @route("/") def index(): usr = getUser() if usr and usr.inRole("student"): redirect("/assigments") return template("index") app = default_app.pop()
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## ## GNU General Public License for more details. ## ## ## ## You should have received a copy of the GNU General Public License ## ## along with this program. If not, see <http://www.gnu.org/licenses/>. ## ## ## ########################################################################### from bottle import default_app, route from modules import utils from modules import query from modules.params import Params from collections import OrderedDict from itertools import groupby app_0_2 = default_app.pop() @app_0_2.route('/errors') def errors(db, lang): params = Params() results = query._gets(db, params) out = OrderedDict() if not params.full: out["description"] = ["lat", "lon", "error_id", "item"] else: out["description"] = [ "lat", "lon", "error_id", "item", "source", "class", "elems", "subclass", "subtitle", "title", "level", "update", "username" ]
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) # application = ErrorHandler( application = PostgresPlugin( LanguageMiddleware( StripPathMiddleware(application, production), default_language = 'en', valid_languages = map(lambda x: x[0], LANGUAGES), clean_url = True # ), ), **postgres_config
import os from bottle import route, run, static_file, jinja2_template, default_app import conf import ajax @route('/<filename:re:\w+.html>') def static(filename): return static_file(filename, os.path.join(conf.ROOT, 'trial')) @route('/static/<filepath:path>') def static(filepath): return static_file(filepath, os.path.join(conf.ROOT, 'static')) root = default_app.pop() root.mount('/ajax/', ajax.app) if __name__ == '__main__': run(app=root, host=conf.HOST, port=8080, reloader=True)
from bottle import route, default_app, request, static_file, hook, redirect from helpers import template, msg, addMenu from user import getUser import os pathToModule = os.path.dirname(__file__) import user import group import lecture import assigment import template as templateWeb # abychom se vyhnuli kolizi s helper fnc @route('/static/<filename:path>') def send_static(filename): return static_file(filename, root = pathToModule+"/static/") @route("/") def index(): usr = getUser() if usr and usr.inRole("student"): redirect("/assigments") return template("index") app = default_app.pop()
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) # application = ErrorHandler( application = PostgresPlugin( LanguageMiddleware(StripPathMiddleware(application, production), default_language='en', valid_languages=map(lambda x: x[0], LANGUAGES), clean_url=True # ), ), **postgres_config)