Пример #1
0
def mock_conn(request, mocker):
    obj = Namespace(conn1=Connection(), conn2=Connection(), conn3=Connection())
    obj.conn1._encode = lambda **kwargs: CONN_ONE_ENCODE
    obj.conn1._decode = lambda **kwargs: CONN_ONE_DECODE
    obj.conn2._encode = lambda **kwargs: CONN_TWO_ENCODE
    obj.conn2._decode = lambda **kwargs: CONN_TWO_DECODE
    obj.conn3._encode = lambda **kwargs: CONN_THR_ENCODE
    obj.conn3._decode = lambda **kwargs: CONN_THR_DECODE
    conns = [obj.conn1, obj.conn2, obj.conn3]
    methods = ['_encode', '_decode', 'do_encode', 'do_decode', 'attach']
    for conn in conns:
        for method in methods:
            mocker.spy(conn, method)
    return obj
Пример #2
0
def get_server_conf(core_ip, source_id, args):

    # establish a synchronus connection to server
    conn = Connection(core_ip)

    # fetch config from server
    server_config = conn.fetch_config()

    # Pull out the configs relevant to this client
    server_conf = {
        'videocaps': server_config['mix']['videocaps'],
        'audiocaps': server_config['mix']['audiocaps']
    }

    if source_id is not None:

        # get conf from server for this source,
        d = server_config[source_id]
        if args.debug:
            pprint(d)

        # stomp all over command line values
        # this is backwards: command line should override conf file.
        for k in d:
            if args.debug:
                print('--{}="{}"'.format(k, d[k]))
            # python argparse converts a-b to a_b, so we will to too.
            args.__setattr__(k.replace("-", "_"), d[k])

    return server_conf, args
Пример #3
0
 def __init__(self, host_name, port_number):
     """
     Instantiate object with the following parameters:
         host_name       ElasticSearch host name
         port_number     ElasticsSearch API port number
     """
     self.es_connection = Connection(host_name, port_number)
Пример #4
0
def get_test_result_set():
    """
    temp added for testing
    :return:
    """
    connection = Connection("dynamodb", "us-west-1")
    storage_obj = DynamoDB(connection=connection.new_connection())
    storage_obj.set_storage_set_name("cs-file-metadata")
    storage_set = storage_obj.get_storage_set()
    result_set = storage_obj.list(storage_set) if storage_set else None
    return result_set
Пример #5
0
 def __init__(self, args):
     """
     Instantiate with an argument parser.
     """
     self.object = args.object
     self.action = args.action
     self.target = args.target
     self.target_index = args.target_index
     self.host = args.host
     self.port = args.port
     self.shards = args.shards
     self.replicas = args.replicas
     self.es_connection = Connection(self.host, self.port)
Пример #6
0
    def __init__(self):
        self.prev_videoMode = "2D"
        self.prev_compState = None
        self.initialized = False

        self.player = XBMCPlayer()
        self.player.register_observer(self)
        self.monitor = XBMCMonitor()
        self.monitor.register_observer(self)
        self.connection = Connection()

        self.updateSettings()
        self.daemon()
Пример #7
0
    async def handle_session(self):
        while True:
            try:
                print('Enter command name:')
                action = sys.stdin.readline().strip()

                if action == 'exit':
                    print('Exiting')
                    return
                elif action == 'help':
                    print('Available commands:\nhelp\nexit')
                    for command in self.type_to_callback:
                        print(command)
                    continue

                if action not in self.type_to_callback:
                    print('Bad command')
                    continue

                request = {'type': action}

                if action not in self.no_auth_check_handlers:
                    username = self.context.get('username')
                    auth_token = self.context.get('auth_token')
                    if not username or not auth_token:
                        print('You should signin first')
                        continue

                    request['auth'] = {'username': username, 'auth_token': auth_token}

                for param in self.type_to_params.get(action, ()):
                    print('Enter {}:'.format(param))
                    request[param] = sys.stdin.readline().strip()

                reader, writer = await asyncio.open_connection(self.server_host, self.server_port)
                conn = Connection(reader, writer)

                await conn.write(request)
                response = await conn.read()
                await conn.close()

                if response.get('code') == 200:
                    self.type_to_callback.get(action)(request, response.get('data', {}))
                else:
                    print('Error occured: {}'.format(response.get('data')))
            except KeyboardInterrupt:
                raise
            except Exception as e:
                logging.exception('Exception occured: {}'.format(e))
                # traceback.print_exc(file=open('client.log', 'a'))
                print('Something went wrong')
Пример #8
0
    def listen_new_connection(self):
        """
        Listen for new connections
        and create the supervisor in case that is not already created
        :return: void
        """
        conn, client_address = self.__socket.accept(
        )  # conn variable is a Socket
        connection = Connection(conn, (client_address[0], self.__socket_port),
                                self.__event, self.__db_file)
        connection.start()

        if not self.__supervisor:
            self.__supervisor = SupervisorThread(self.__event)
            self.__supervisor.start()
Пример #9
0
    async def handle(self, reader, writer):
        try:
            addr = writer.get_extra_info('peername')
            logging.info('Incoming request from {}'.format(addr))

            conn = Connection(reader, writer)

            request = await conn.read()
            response = Handler(self.auth_handler).handle_request(request)

            await conn.write(response)
            await conn.close()
        except KeyboardInterrupt:
            raise
        except Exception as e:
            logging.exception('Unhandled exception occured: {}'.format(e))
Пример #10
0
def get_result_set(region, bucket, table, base):
    """get result set from storage object
    """
    connection = Connection(base, region)
    base = base.lower()
    storage_obj = None

    if base == "s3":
        storage_obj = S3(connection=connection.new_connection())
        storage_obj.set_storage_set_name(bucket)
    elif base == "dynamodb":
        storage_obj = DynamoDB(connection=connection.new_connection())
        storage_obj.set_storage_set_name(table)
    storage_set = storage_obj.get_storage_set()
    result_set = storage_obj.list(storage_set) if storage_set else None

    return result_set
Пример #11
0
def processChangelog(basepath='~/.jot/jot.changelog'):
    '''Look for foreign changelogs and update and delete them'''
    from lib.connection import Connection
    path = matchPath(basepath,mustExist=False) + '.*'
    logfiles = glob.glob(path)

    def writeQuery(db,log):
        '''Executes the query and records the transaction'''
        if db.matchIdentifier(log.identifier,quiet=True) is None:
            if log.values is not None:
                db.rawQuery(log.query,log.values,commit=False)
            else:
                db.rawQuery(log.query,commit=False)
            transaction = 'insert into transactions(hash,ts) values("%s","%s")' % (log.identifier,time.time()) 
            db.rawQuery(transaction,commit=False)
            return True
        return False

    if len(logfiles) > 0:
        print 'Found new changelog. Updating local database...'
        db = Connection(table='transactions',verbose=False)
        changesCount = 0
        for logfile in logfiles:
            fp = open(logfile,'rb')
            while True:
                try:
                    log = pickle.load(fp)
                    if writeQuery(db,log):
                        changesCount += 1
                except EOFError:
                    break
            fp.close()
            os.remove(logfile)
        db.commit()
        if changesCount > 0:
            print 'Done.'
            print decorate('OKGREEN',str(changesCount) + ' changes were made.')
        else:
            print 'Nothing to update.'

    return True
Пример #12
0
    "cisco": {
        "platform": "ios",
    },
    "arista": {"platform": "eos"},
    "juniper": {"platform": "junos"},
}

defaults_dict = {
    "username": "******",
    "password": "******",
    "data": {"key3": "value3"},
}

from lib.connection import Connection
from lib.constant import SCRAPLI

command = "show version"
import datetime

a = datetime.datetime.now()

conn = Connection(SCRAPLI)
conn.open(hosts_dict, groups_dict, defaults_dict)
result_dt = conn.send_command(command)
print(result_dt["cisco3"].result)
conn.close()

b = datetime.datetime.now()
c = b - a
print("Executation time", SCRAPLI, c.seconds)
Пример #13
0
hosts_dict = {"cisco3": {"hostname": "100.100.0.10"}}

defaults_dict = {
    "username": "******",
    "password": "******",
    "port": 22,
    "platform": "cisco_ios"
}

from lib.connection import Connection
from lib.constant import NETMIKO
from lib.constant import SCRAPLI

command = "show version"

import timeit

# conn = Connection(NETMIKO)
# conn.open(hosts=hosts_dict, defaults=defaults_dict)
# result_dt = conn.send_command(command)
# print(result_dt["cisco3"].result)
# conn.close()

conn1 = Connection(NETMIKO)
conn1.open(hosts=hosts_dict, defaults=defaults_dict)
result_dt = conn1.send_command(command)
print(result_dt["cisco3"].result)
conn1.close()
Пример #14
0
                        "--base",
                        type=str,
                        help="s3 | dynamodb",
                        default="s3",
                        required=False)

    # logging
    logging.config.fileConfig('logging.ini',
                              disable_existing_loggers=False,
                              defaults={'logfilename': LOG_PATH})
    logger = logging.getLogger(__name__)

    # FIXME - file logging
    fh = logging.FileHandler(LOG_PATH)
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    fh.setFormatter(formatter)
    logger.addHandler(fh)

    # parse args
    args = parser.parse_args()
    db_connection = Connection("dynamodb", args.region)
    db_table = args.table
    db = DynamoDB(connection=db_connection.new_connection())
    s3_connection = Connection("s3", args.region)
    s3_bucket = args.bucket
    s3 = S3(connection=s3_connection.new_connection())
    if db and s3:
        main(args.region, args.bucket, args.table, args.base, args.threadcount)
    else:
        raise ImportError("No DB connection")
Пример #15
0
def main():
    initial_path = os.path.dirname(os.path.abspath(__file__))

    HOST, PORT, REVERSE, PUB_KEY_FILE, PRV_KEY_FILE, KN_HOSTS_FILE = read_conf(
    )

    # Comprobar que exista un fichero con la clave pública del cliente
    if os.path.isfile(KN_HOSTS_FILE):
        with open(KN_HOSTS_FILE, "rb") as f:
            known_hosts = f.read()
        known_hosts = known_hosts.split("\n")
    else:
        print '[!] ERROR: El fichero {} debe existir.'.format(KN_HOSTS_FILE)
        sys.exit(1)

    while True:
        time.sleep(1)

        # Creación del socket
        conn = Connection(HOST, PORT)

        try:
            if REVERSE == '1':
                conn.connect()
            else:
                conn.listen(timeout=5)

            keyring = Keyring()

            # Lee los ficheros de claves pub/priv
            with open(PRV_KEY_FILE, 'rb') as f:
                prv_key = f.read()
            with open(PUB_KEY_FILE, 'rb') as f:
                pub_key = f.read()

            # Recibe la clave pública del cliente
            cli_pub_key = conn.receive()

            # Si no reconoce la clave pub del cliente, informa de que se cierra la conexión
            if cli_pub_key not in known_hosts:
                conn.send(':ERR:')
                sys.exit(1)
            # Si reconoce la clave pub del cliente, le envía su clave pública
            conn.send(pub_key)

            # Recibe firma de autenticación del cliente y la comprueba
            cli_signature = conn.receive()
            sign_valid = keyring.verify(cli_pub_key, cli_signature)
            # Si es válida, envía su firma de autenticación
            if sign_valid:
                signature = keyring.sign(prv_key)
                conn.send(signature)
            else:
                conn.send(':ERR:')
                sys.exit(1)

            # Si el cliente no acepta la firma, cierra el programa
            auth = conn.receive()
            if auth == ':ERR:':
                sys.exit(1)

            # Marca de sincronización
            conn.send(':SYNC:')
            # Intercambio de clave de sesión mediante PKI
            session_key_crypted = conn.receive()
            session_key = keyring.decipherRSA(session_key_crypted, prv_key)

            # Una vez establecida e intercambiada la clave de sesión, asociamos el keyring a la conexión
            keyring.session_key = session_key
            conn.keyring = keyring

            shell = Shell(conn)
            shell.start()
            os.chdir(initial_path)  # Por si el cliente se cambió de directorio

        except:
            pass
Пример #16
0
 def test_interface_functions(self):
     conn = Connection()
     conn._encode()
     conn._decode()
Пример #17
0
 def connect(self, next_neuron, weight = 0):
     Connection(self, next_neuron, weight)
     return self
Пример #18
0
def main():
    HOST, PORT, REVERSE, PUB_KEY_FILE, PRV_KEY_FILE, KN_HOSTS_FILE = read_conf(
    )

    # Si se pasa dirección y/o puerto como argumento, sobreescribirlo
    addr, port = read_args()
    if addr: HOST = addr
    if port: PORT = port

    # Si existe el known_hosts, leerlo y convertirlo en una lista
    if os.path.isfile(KN_HOSTS_FILE):
        with open(KN_HOSTS_FILE, "rb") as f:
            known_hosts = f.read()
        known_hosts = known_hosts.split("\n")
    else:
        known_hosts = False

    # Creación del socket
    conn = Connection(HOST, PORT)

    try:
        if REVERSE == '1':
            conn.listen(timeout=10)
        else:
            conn.connect()

        keyring = Keyring()

        # Lee los ficheros de claves pub/priv
        with open(PRV_KEY_FILE, 'rb') as f:
            prv_key = f.read()
        with open(PUB_KEY_FILE, 'rb') as f:
            pub_key = f.read()

        # Envía su clave pública al servidor
        conn.send(pub_key)

        # Recibe la clave pública del servidor
        srv_pub_key = conn.receive()
        if srv_pub_key == ':ERR:':
            print '{}[!]{} ERROR: El servidor no reconoce tu clave pública.'.format(
                color.RED, color.END)
            sys.exit(1)

        # Comparación de clave pública recibida con las contenidas en el known_hosts
        if (not known_hosts) or (srv_pub_key not in known_hosts):
            add_srv_to_known_hosts = raw_input(
                "{}[!]{} WARNING: La clave pública de este servidor no se encuentra almacenada:\n{} \nSi lo desea, puede añadirla [y/n] >>> "
                .format(color.YELLOW, color.END, srv_pub_key))
            if add_srv_to_known_hosts.lower() == "y":
                with open(KN_HOSTS_FILE, "ab") as f:
                    f.write(srv_pub_key + "\n")

        # Envía firma de autenticación
        signature = keyring.sign(prv_key)
        conn.send(signature)

        srv_signature = conn.receive()
        # Si recibe error de autenticación, informa y cierra el programa
        if srv_signature == ':ERR:':
            print '{}[!]{} ERROR: La autenticación ha fallado'.format(
                color.RED, color.END)
            sys.exit(1)

        # Si logra autenticarse, comprueba la firma del servidor
        print '{}[+]{} Cliente autenticado correctamente'.format(
            color.GREEN, color.END)
        sign_valid = keyring.verify(srv_pub_key, srv_signature)
        if sign_valid:
            conn.send(':OK:')
            print '{}[+]{} Servidor autenticado correctamente'.format(
                color.GREEN, color.END)
        else:
            conn.send(':ERR:')
            print '{}[!]{} ERROR: La autenticación ha fallado'.format(
                color.RED, color.END)
            sys.exit(1)

        # Marca de sincronización
        sync = conn.receive()

        # Intercambio de clave de sesión mediante PKI
        session_key = keyring.genSessionKey()
        session_key_crypted = keyring.cipherRSA(session_key, srv_pub_key)
        conn.send(session_key_crypted)
        print '{}[+]{} Intercambiando clave de sesión...'.format(
            color.BLUE, color.END)
        # Una vez establecida e intercambiada la clave de sesión, asociamos el keyring a la conexión
        keyring.session_key = session_key
        conn.keyring = keyring

        shell = Shell(conn)
        shell.start()

    except conn.timeout:
        print '\n{}[!]{} El servidor está desconectado.\n'.format(
            color.RED, color.END)