Ejemplo n.º 1
0
async def async_test_e2e(loop: asyncio.AbstractEventLoop, password: str):
    local = Local(loop, password, '127.0.0.1', LOCAL_PORT, '127.0.0.1',
                  SERVER_PORT)
    server = Server(loop, password, '127.0.0.1', SERVER_PORT)
    asyncio.ensure_future(local.listen())
    asyncio.ensure_future(server.listen())
    asyncio.ensure_future(remote_listen(loop))

    client_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    await loop.sock_connect(client_sock, ('127.0.0.1', LOCAL_PORT))

    # greeting
    client_hello = bytes((0x05, 0x01, 0x00))
    await loop.sock_sendall(client_sock, client_hello)
    server_hello = await loop.sock_recv(client_sock, BUFFER_SIZE)
    assert server_hello == bytes((0x05, 0x00))
    # request: connect to remote 127.0.0.1:34567
    socks_request = bytes(
        (0x05, 0x01, 0x00, 0x01, 0x7f, 0x00, 0x00, 0x01, 0x87, 0x07))
    await loop.sock_sendall(client_sock, socks_request)
    socks_response = await loop.sock_recv(client_sock, BUFFER_SIZE)
    assert socks_response == bytes(
        (0x05, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00))
    # pipe
    msg = b'hello world'
    await loop.sock_sendall(client_sock, msg)
    msg_reply = await loop.sock_recv(client_sock, BUFFER_SIZE)
    assert msg_reply == b'Reply: hello world'
Ejemplo n.º 2
0
    def __init__(self):
        """ Inicializa los scopes de las variables : Temporales, Globales,
		Locales y Constantes.
		"""
        self.tmp = Temporal()
        self.glob = Globs()
        self.loc = Local()
        self.const = Constant()
        self.max_memory = 20000
        self.current_used_memory = 0
Ejemplo n.º 3
0
 def setUp(self):
     self.listenAddr = ("127.0.0.1", 11111)
     self.remoteAddr = ("127.0.0.1", 22222)
     self.remoteServer = socket.socket()
     self.remoteServer.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
     self.remoteServer.bind(self.remoteAddr)
     self.remoteServer.listen(socket.SOMAXCONN)
     self.remoteServer.setblocking(False)
     pwd = randomPwd()
     self.cipher = Cipher.NewCipher(pwd)
     self.loop = asyncio.new_event_loop()
     self.local = Local(
         loop=self.loop,
         pwd=pwd,
         listenAddr=self.listenAddr,
         remoteAddr=self.remoteAddr,
     )
     self.msg = bytearray(b"hello world")
     self.encrypted_msg = self.msg.copy()
     self.cipher.encode(self.encrypted_msg)
Ejemplo n.º 4
0
    def __init__(self):
        credentials = self.get_credentials()
        http = credentials.authorize(httplib2.Http())
        self.service = discovery.build('drive', 'v3', http=http)

        self.local = Local(LOCAL_BACKUP_DIRECTORY)

        self.files = []  # all files ever found

        self.check_interrupt = False
        self.check_ready = True
        self.check_counters = []

        self.sync_queue = []
        self.syncing = None
        self.check_prioity_depth = 1  #the depth to check for files before procuessing the sync queue
        self.failed_sync = []

        self.echo_on = False
        self.logs = []
        self.templog = False
Ejemplo n.º 5
0
Archivo: dv.py Proyecto: wehu/pydv
def main():

    global server_p

    # parsing arguments
    (opts, args) = args_parse()

    in_q = Queue()
    out_q = Queue()

    logger.info('running dv.py')
    # start agent server
    #loop = asyncio.get_event_loop()
    server_p = Process(target=start_agent_server,
                       args=(
                           in_q,
                           out_q,
                           path.abspath(opts.out_dir),
                           opts.verbose,
                       ))
    #server_p = Thread(target=start_agent_server, args=(loop, in_q, out_q,))
    server_p.start()

    try:
        # waiting for server started
        host, port = in_q.get()

        #logger.info("agent server started on {}:{}".format(host, port))

        # set gcf engine
        if opts.gcf == 'local':
            GCFEngine.set_imp(
                Local(host, port, path.abspath(opts.out_dir), opts.verbose))
        else:
            if opts.gcf == 'lsf':
                GCFEngine.set_imp(
                    LSF(host, port, path.abspath(opts.out_dir), opts.verbose))
            else:
                raise Exception('unsupported gcf engine {}'.format(opts.gcf))

        # config job engine
        JobEngine.connect(in_q, out_q)
        JobEngine.out_dir = path.abspath(opts.out_dir)
        logger.info('max agents = {}'.format(opts.max_agents))
        JobEngine.max_cmds = opts.max_agents

        # load files
        require('loader')
        if opts.patchfile:
            for f in opts.patchfile:
                require(f)

        # evaluate experssions
        @visitor
        def top():
            @join
            def body(self):
                if opts.expr:
                    for e in opts.expr:

                        @spawn(self)
                        def body(ee=e):
                            res = eval(ee, get_ns(), get_ns())
                            if type(res) == GeneratorType:
                                yield from res
                            return res

                if opts.test:

                    @spawn(self)
                    def body():
                        res = run_test(*opts.test,
                                       action=opts.action,
                                       where=opts.where)
                        if type(res) == GeneratorType:
                            yield from res
                        return res

            yield from body()

        # run
        while True:
            JobEngine.run()
            Scheduler.run()
            if JobEngine.is_waiting() or Scheduler.is_waiting():
                next
            else:
                break
        for t in Test.test_status:
            if Test.test_status[t] == 'passed':
                logger.info("*** test '{}' passed".format(t))
            else:
                logger.error("*** test '{}' failed".format(t))
        if top.exception:

            def print_exception(e, indent=0):
                if isinstance(e, Exception):
                    for l in extract_tb(e.__traceback__):
                        logger.debug((" " * indent) + str(l))
                if not isinstance(e, Exception):
                    logger.error((" " * indent) + str(e))
                    return
                for i in e.args:
                    if not isinstance(i, list):
                        i = [i]
                    for j in i:
                        print_exception(j, indent + 2)

            print_exception(top.exception)
            logger.error('dv.py failed')
            #raise top.exception
        else:
            logger.info('dv.py passed')
    finally:
        event.notify('dvpy_done')
        cleanup()
Ejemplo n.º 6
0
def main():
    parser = argparse.ArgumentParser(
        description='Sync current folder to your flickr account.')

    parser.add_argument('--monitor',
                        action='store_true',
                        help='Start monitoring daemon.')
    parser.add_argument(
        '--starts-with',
        type=str,
        help='Only sync those paths that start with this text, e.g. "2015/06."'
    )
    parser.add_argument(
        '--download',
        type=str,
        help='Download photos from flickr. Specify a path or use "." for all.')
    parser.add_argument('--dry-run',
                        action='store_true',
                        help='Do not download or upload anything.')
    parser.add_argument('--ignore-videos',
                        action='store_true',
                        help='Ignore video files.')
    parser.add_argument('--ignore-images',
                        action='store_true',
                        help='Ignore image files.')
    parser.add_argument(
        '--ignore-ext',
        type=str,
        help=
        'Comma separated list of filename extensions to ignore, e.g. "jpg,png".'
    )
    parser.add_argument('--fix-missing-description',
                        action='store_true',
                        help='Replace missing set description with set title.')
    parser.add_argument('--version',
                        action='store_true',
                        help='Output current version: ' + version)
    parser.add_argument('--sync-path',
                        type=str,
                        default=os.getcwd(),
                        help='Specify sync path (default: current dir).')
    parser.add_argument(
        '--sync-from',
        type=str,
        help=
        'Only one supported value: "all". Upload anything not on flickr. Download anything not on the local filesystem.'
    )
    parser.add_argument(
        '--custom-set',
        type=str,
        help='Customize set name from path with regex, e.g. "(.*)/(.*)".')
    parser.add_argument(
        '--custom-set-builder',
        type=str,
        help=
        'Build custom set title, e.g. "{0} {1}" joins first two groups (default behavior merges groups using a hyphen).'
    )
    parser.add_argument(
        '--update-custom-set',
        action='store_true',
        help=
        'Updates set title from custom-set (and custom-set-builder, if given).'
    )
    parser.add_argument(
        '--custom-set-debug',
        action='store_true',
        help=
        'When testing custom sets: ask for confirmation before creating an album.'
    )
    parser.add_argument('--username',
                        type=str,
                        help='Token username argument for API.')
    parser.add_argument('--keyword',
                        action='append',
                        type=str,
                        help='Only upload files matching this keyword.')

    args = parser.parse_args()

    if args.version:
        logger.info(version)
        exit()

    # Windows OS
    args.is_windows = os.name == 'nt'
    args.sync_path = args.sync_path.rstrip(os.sep) + os.sep
    if not os.path.exists(args.sync_path):
        logger.error('Sync path does not exist.')
        exit(0)

    local = Local(args)
    remote = Remote(args)
    sync = Sync(args, local, remote)
    sync.start_sync()
Ejemplo n.º 7
0
#!/usr/bin/python
#-*- coding: utf-8 -*-

import config
from remote import Remote
from local import Local
from base import log
import types

ins = Remote() if config.is_dev else Local()
_remote_cmd_max_len = 800
_escape_obj = { # str: replace_to
    '$': r'\$',
    '&': r'\&',
    '#': r'\#',
    ';': r'\;',
    '?': r'\?',
    '[': r'\[',
    ']': r'\]',
    '(': r'\(',
    ')': r'\)',
    '*': r'\*',
    '|': r'\|',
    '>': r'\>'
}

def getRemoteIP():
    rip = ins.getLocalIP() if config.is_dev else None
    return rip

def _decorate_split_cmds_if_use_remote(fn):
Ejemplo n.º 8
0
def main():
    parser = argparse.ArgumentParser(
        description='Sync current folder to your flickr account.')
    parser.add_argument('--monitor',
                        action='store_true',
                        help='starts a daemon after sync for monitoring')
    parser.add_argument(
        '--starts-with',
        type=str,
        help='only sync that path starts with this text, e.g. "2015/06"')
    parser.add_argument(
        '--download',
        type=str,
        help='download the photos from flickr, specify a path or . for all')
    parser.add_argument('--ignore-videos',
                        action='store_true',
                        help='ignore video files')
    parser.add_argument('--ignore-images',
                        action='store_true',
                        help='ignore image files')
    parser.add_argument(
        '--ignore-ext',
        type=str,
        help='comma separated list of extensions to ignore, e.g. "jpg,png"')
    parser.add_argument('--version',
                        action='store_true',
                        help='output current version: ' + version)
    parser.add_argument(
        '--sync-path',
        type=str,
        default=os.getcwd(),
        help='specify the sync folder (default is current dir)')
    parser.add_argument(
        '--sync-from',
        type=str,
        help=
        'Only supported value: "all". Uploads anything that isn\'t on flickr, and download anything that isn\'t on the local filesystem'
    )
    parser.add_argument(
        '--custom-set',
        type=str,
        help='customize your set name from path with regex, e.g. "(.*)/(.*)"')
    parser.add_argument(
        '--custom-set-builder',
        type=str,
        help=
        'build your custom set title, e.g. "{0} {1}" to join the first two groups (default merges groups with hyphen)'
    )
    parser.add_argument(
        '--update-custom-set',
        action='store_true',
        help=
        'updates your set title from custom-set (and custom-set-builder, if given)'
    )
    parser.add_argument(
        '--custom-set-debug',
        action='store_true',
        help=
        'for testing your custom sets, asks for confirmation when creating an album on flickr'
    )
    parser.add_argument(
        '--username', type=str,
        help='token username')  # token username argument for api
    parser.add_argument('--keyword',
                        action='append',
                        type=str,
                        help='only upload files matching this keyword')

    args = parser.parse_args()

    if args.version:
        logger.info(version)
        exit()

    # validate args
    args.is_windows = os.name == 'nt'
    args.sync_path = args.sync_path.rstrip(os.sep) + os.sep
    if not os.path.exists(args.sync_path):
        logger.error('Sync path does not exists')
        exit(0)

    local = Local(args)
    remote = Remote(args)
    sync = Sync(args, local, remote)
    sync.start_sync()
Ejemplo n.º 9
0
import serial
import firebase_admin
from firebase_admin import firestore
from sender import Sender
from receiver import Receiver
from local import Local
from device_data import DeviceData

# serial_port = serial.Serial("/dev/ttyACM0", 9600)

uno = serial.Serial("/dev/ttyACM0", 9600)
nano = serial.Serial("/dev/ttyUSB0", 9600)

data = DeviceData()

cred = firebase_admin.credentials.Certificate("smarthome-ee796-firebase-adminsdk-e5uty-d2e5e8672e.json")
firebase_admin.initialize_app(cred)
db = firestore.client()

localObj = Local(uno, db)
sender_obj = Sender(uno, nano, db, data)
receiver_obj = Receiver(uno, db, data)

sender_obj.start_loop()
Ejemplo n.º 10
0
 def __init__(self):
     self._local = Local()
Ejemplo n.º 11
0
    def send_command(self, command, search, thread_num, exec_cmd, startIP, endIP, ipfile):
        """Execute a command"""
        if search == "censys":
            self.search = Censys()
        elif search == "zoomeye":
            self.search = Zoomeye()
        elif search == "shodan":
            self.search = Shodan()
        elif search == "local":
            self.search = Local()
        else:
            print "you got a wrong type of search engine, you can select censys, shodan or zoomeye as your scan engine."
            sys.exit()
        
        if self.setQuery(command):
            return {'prompt': '', 'busy': False, 'data': 'QUERY => %s\n' % self.query}
        elif self.setPage(command):
            return {'prompt': '', 'busy': False, 'data': 'PAGE => %d\n' % self.page}
        else:
            if command == "exploit\n" or command == "run\n":
                if not self.search:
                    print "please select a search engine using the -s or --search option."
                    sys.exit()
                
                if (self.module and self.moduleType) or exec_cmd:
                    if (startIP and endIP) or ipfile:
                        args = (self.queue, self.STOP_ME, startIP, endIP, ipfile)
                    else:
                        if self.query:
                            self.search.getConfig()
                            args = (self.query, self.page, self.queue, self.STOP_ME)
                        else:
                            return {'prompt': '', 'busy': False, 'data': 'QUERY must be setted\n'}
                    threads = []
                    t1 = threading.Thread(target = self.search.searchIP, args = args)
                    threads.append(t1)
                    t2 = threading.Thread(target=self.DoExploit, args=(exec_cmd, command, thread_num))
                    threads.append(t2)
                    for t in threads:
                        t.setDaemon(True)
                        t.start()

                    for t in threads:
                        t.join()
                    
                    result = {'prompt': '', 'busy': False, 'data': '\n'}
                else:
                    return {'prompt': '', 'busy': False, 'data': 'please select the module\n'}
            else:
                isSuccess = self.client.call('console.write', [self.console_id, command])
                if isSuccess.has_key('error'):
                    self.login()
                    self.client.call('console.write', [self.console_id, command])
                sleep(0.5)
                result = self.client.call('console.read', [self.console_id])
                while result['busy']:
                    if result['data']:
                        print result['data']
                    sleep(0.5)
                    result = self.client.call('console.read', [self.console_id])
                
                if command == "show options\n":
                    if exec_cmd:
                        result['data'] = "%s   command              %s\n" % (result['data'], exec_cmd)
                    result['data'] = "%s   QUERY             %s\n" % (result['data'], self.query)
                    result['data'] = "%s   PAGE              %s\n" % (result['data'], self.page)

                if command.startswith("use"):
                    module = command.split(' ')[1].strip()
                    self.moduleType = module[:module.find('/')]
                    self.module = module[module.find('/')+1:]

                if command.startswith("set"):
                    options = command.split(' ')
                    self.opts[options[1]] = options[2].strip()
            
            return result
Ejemplo n.º 12
0
            'tools.staticdir.on': True,
            'tools.staticdir.dir': os.path.abspath('./public')
        },
        '/slides': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': os.path.abspath('./slides')
        },
        '/': {
            'tools.sessions.on': True
        }
    }    

    if args.daemonize:
        d = Daemonizer(cherrypy.engine, stderr='/var/log/missionary_server.log')
        d.subscribe()
        PIDFile(cherrypy.engine, '/var/run/missionary_server.pid').subscribe()
        DropPrivileges(cherrypy.engine, uid=1000, gid=1000).subscribe()

    # cherrypy.config.update({'log.screen': False,
    #                         'log.access_file': '',
    #                         'log.error_file': ''})

    settings = Settings('settings.json')
    cherrypy.tree.mount(Root(settings), '/', conf)
    cherrypy.tree.mount(SlideShow('./slides'), '/slideshow', conf)
    cherrypy.tree.mount(Local(), '/local')
    cherrypy.tree.mount(Missionary(settings), '/missionary')
    cherrypy.tree.mount(PhotoUploader(os.path.abspath('./slides')), '/photos', conf)
    cherrypy.tree.mount(settings, '/settings', conf)
    cherrypy.quickstart(Mission(settings), '/mission', conf)
Ejemplo n.º 13
0
import traceback
import sys
from threading import Lock
import re
import datetime
import functools
import logging
from uuid import uuid1
from http import RESPONSE_STATUSES, RESPONSE_HEADER_DICT, HEADER_X_POWERED_BY, RE_RESPONSE_STATUS
from http import RedirectError, bad_request, not_found, HttpError
from http import to_str, to_unicode, quote, unquote
from utils import Dict, UTC
from local import Local


ctx = Local()


def route(path, methods=None):
    """
    route decorator
    :param path: the url path
    :param methods: HTTP's Methods, defaults is 'GET'
    :return:
    """
    if methods is None:
        methods = ['GET']

    def _decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kw):
Ejemplo n.º 14
0
def main():
    parser = argparse.ArgumentParser(
        description='Upload, download or sync photos and videos to Flickr.')
    parser.add_argument(
        '--custom-set',
        type=str,
        help=
        'customize set title from path using standard regex, e.g. "(.*)/(.*)"')
    parser.add_argument(
        '--custom-set-builder',
        type=str,
        help=
        'build a custom set title using matched groups, e.g. "{0}{1}" joins first two "(.*)/(.*)"'
    )
    parser.add_argument(
        '--download',
        type=str,
        help='download photos; specify a path or use "." for all')
    parser.add_argument(
        '--dry-run',
        action='store_true',
        help='report actions but do not change local/remote sets')
    parser.add_argument('--fix-missing-description',
                        action='store_true',
                        help='replace missing set description with set title')
    parser.add_argument(
        '--ignore-extensions',
        type=str,
        help='comma separated list of filename extensions to ignore')
    parser.add_argument(
        '--ignore-images',
        action='store_true',
        help='ignore image files: jpg, jpeg, png, gif, tif, tiff, bmp')
    parser.add_argument(
        '--ignore-videos',
        action='store_true',
        help=
        'ignore video files: m4v, mp4, avi, wmv, mov, mpg, mpeg, 3gp, mts, m2ts, ogg, ogv'
    )
    parser.add_argument(
        '--keywords',
        action='append',
        type=str,
        help='only upload files with IPTC metadata matching these keywords')
    parser.add_argument(
        '--nobrowser',
        action='store_true',
        help='support manual authentication when no web browser is available')
    parser.add_argument('--starts-with',
                        type=str,
                        help='only upload paths starting with this text')
    parser.add_argument(
        '--sync',
        action='store_true',
        help=
        'upload anything not on Flickr; download anything not on local filesystem'
    )
    parser.add_argument(
        '--sync-path',
        type=str,
        default=os.getcwd(),
        help=
        'sync path (default: current dir); individual files in --sync-path root are not synced to avoid disorganized Flickr sets'
    )
    parser.add_argument('--version',
                        action='store_true',
                        help='print current version: ' + version)

    args = parser.parse_args()

    args.windows = os.name == "nt"

    if args.version:
        logger.info('--version %s', version)
        exit(0)
    else:
        logger.debug('--version %s', version)

    args.sync_path = args.sync_path.rstrip(
        os.sep) + os.sep  # ensure sync path ends with "/"
    if not os.path.exists(args.sync_path):
        logger.error('--sync-path "%s" does not exist', args.sync_path)
        exit(0)

    local = Local(args)
    remote = Remote(args)
    sync = Sync(args, local, remote)
    sync.start_sync()