Пример #1
0
 def prepare_client_instances(self):
     for index, ip in enumerate(self.validator_ip_list):
         self.clients.append(
             Client(ip,
                    role="validator",
                    autonity_path=self.autonity_path,
                    bootnode_path=self.bootnode_path,
                    index=index))
     for index, ip in enumerate(self.participant_ip_list):
         self.clients.append(
             Client(ip,
                    role="participant",
                    autonity_path=self.autonity_path,
                    bootnode_path=self.bootnode_path,
                    index=index + len(self.validator_ip_list)))
Пример #2
0
def test_latency(server_list):
    # test latency of uniform key for put
    print("Testing latency...")
    client = Client(server_list)
    key_list = [
        ''.join([
            random.choice(string.ascii_letters + string.digits)
            for n in range(32)
        ]) for x in range(num_key)
    ]
    value = ''.rjust(1024, '0')
    failure = 0
    elapsed_time = 0
    for i in range(10):
        for key in key_list:
            start = time.time()
            old_val, rtn = client.put(key, value)
            if (rtn == -1):
                failure += 1
            elapsed_time += time.time() - start

    print(failure)
    print(elapsed_time)
    latency = elapsed_time / (10 * num_key) * 1e3
    print("Average latency for uniform key: {:.3f} ms".format(latency))
Пример #3
0
def main():
    arguments = docopt(__doc__, version=__version__)

    level = getattr(logging, arguments.get("--level").upper())

    handlers = [StreamHandler()]
    log = logging.getLogger(__name__)
    logging.basicConfig(
        level=level,
        format="%(asctime)s %(name)-15s: %(levelname)-8s %(message)s",
        handlers=handlers)

    port = arguments.get("--port")

    # Are we a server or a client?
    if arguments.get("server"):
        log.debug("We are a server!")
        log.debug("Running on: {} port: {}".format("localhost", port))
        server = Server(port)
        server.serve()
    else:
        server_ip = arguments.get("<server_ip>")
        log.debug("We are a client!")
        log.debug("Running on: {} port: {}".format(server_ip, port))
        client = Client(server_ip, port)
        client.run()
Пример #4
0
def home():

    if request.method == 'POST':
        email = request.form['signInEmail']
        password = request.form['signInPassword']

        global client
        global NICK

        users = db.child("users").get()
        if users.val() != "none":
            for user in users.each():
                userList.append(user.val())

            for user in userList:
                newUser = user.get("username")
                newUserMail = user.get("email")

                if newUserMail == email:
                    NICK = newUser
            client = Client(NICK)
            print(NICK)

        try:
            auth.sign_in_with_email_and_password(email, password)
            # user_id = auth.get_account_info(user['idToken'])
            # session['usr'] = user_id
            # print(session['usr'])
            return render_template("chat.html")
        except:
            unseccessful = "please check your e-mail or password"
            return render_template("index.html", unmessage=unseccessful)

    return render_template("index.html")
Пример #5
0
def main():
    args = parse_arguments()

    if args.count not in range(1000000):
        print("Bad number of packets to transmit.", file=sys.stderr)
        return

    try:
        cli = Client(args.server, args.count, args.verbose, args.dest)
        if args.ping:
            cli.run_direct_ping()
        elif args.reverse:
            cli.run_reverse_ping()
        else:
            if not args.dest:
                print("Destination ip and port needed", file=sys.stderr)
                return
            elif args.dest and len(args.dest.split(':')) != 2:
                print("Destination ip must be likely <ip>:<port>",
                      file=sys.stderr)
                return
            cli.run_proxy_ping()
        cli.close()
    except (gaierror, ConnectionRefusedError) as e:
        print(f"Unable to connect to server: {str(e)}", file=sys.stderr)
    except ConnectionClosedException as e:
        print(f"Connection Closed: {str(e)}", file=sys.stderr)
Пример #6
0
def get_user_input():
    client = Client()
    email = request.form.get('email') or ""
    password = request.form.get('password') or ""
    url = request.form.get('url') or ""
    is_private_mode = 0
    if request.form.get('private'):
        is_private_mode = 1
    if "proxy-settings" in url:
        return proxy_settings()
    # if private mode selected or email or password is passed in...
    if is_private_mode == 1 or (email != "" or password != ""):
        data = {
            'url': url,
            'is_private_mode': is_private_mode,
            'client_ip': request.remote_addr,
            'http_version': request.environ.get('SERVER_PROTOCOL'),
            'user_name': email,
            'password': password
        }
    else:
        # makes new client. request_to_proxy....
        data = {
            'url': url,
            'is_private_mode': is_private_mode,
            'client_ip': request.remote_addr,
            'http_version': request.environ.get('SERVER_PROTOCOL')
        }

    client.request_to_proxy(data)
    res = client.response_from_proxy()

    html_body = res.split("\r\n")[-1]
    return html_body
Пример #7
0
def main():
    parser = argparse.ArgumentParser(description='Games')
    subparsers = parser.add_subparsers(title='module', dest='module')
    subparsers.required = True
    subparsers.add_parser('server', help='start the server')
    subparsers.add_parser('client', help='start a client')

    args = parser.parse_args()

    if args.module == 'server':
        server = Server()
        try:
            server.start()
        except BaseException as e:
            logger.error('Process interrupted, stopping the server',
                         exc_info=e)
        finally:
            server.stop()
    elif args.module == 'client':
        client = Client()
        try:
            client.connect()
            client.run()
        except BaseException as e:
            logger.error('Process interrupted, disconnecting the client',
                         exc_info=e)
        finally:
            client.disconnect()
    else:
        print('unknown module {}'.format(args.module), file=sys.stderr)
Пример #8
0
def main():
    parser = argparse.ArgumentParser(
        description='Creating and management discord server with python')
    parser.add_argument('-t',
                        '--token',
                        type=str,
                        metavar='TOKEN',
                        required=True,
                        help='Your developer bot token from discord')
    parser.add_argument('-g',
                        '--guild',
                        type=int,
                        metavar='ID',
                        required=True,
                        help='Your guild id, server id from discord')
    parser.add_argument('-s',
                        '--setup',
                        type=bool,
                        metavar='BOOL',
                        default=False,
                        help="Create server from scratch (True/False)")
    parser.add_argument('-l',
                        '--logger',
                        type=int,
                        metavar='ID',
                        default=20,
                        help='Custom logger output (ID  from logging module')
    args = parser.parse_args()
    client = Client(args.guild, run_setup=args.setup, log_level=args.logger)
    client.run(args.token)
Пример #9
0
    def start(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.bind((consts.TCP_IP, consts.TCP_PORT))
        sock.listen(1)

        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sockSsl = ssl.wrap_socket(sock,
                                  keyfile="network/certs/server.key",
                                  certfile="network/certs/serverCert.pem",
                                  server_side=True)

        threads = []
        print("Server active, waiting for client connection")
        while True:
            try:
                connection = None
                connection, addr = sockSsl.accept()

                newthread = Client(connection, self.dbc)
                newthread.start()
                threads.append(newthread)
            except Exception as e:
                print(e)

        for t in threads:
            t.join()
Пример #10
0
 def initClient(self):
     from client.client import Client
     if NO_SETTINGS:
         messages = 100
     else:
         messages = settings["max_messages"]
     self.client = Client(max_messages=messages)
Пример #11
0
def rm(path):
    """Delete a file or directory"""
    cl = Client()
    res = cl.delete(path)
    stat = res['status']
    if stat != Status.ok:
        print(Status.description(stat))
Пример #12
0
def mkdir(path):
    """Create a directory"""
    cl = Client()
    res = cl.create_dir(path)
    stat = res['status']
    if stat != Status.ok:
        print(Status.description(stat))
Пример #13
0
def main():
    """
    Run the server
    :return:
    """
    client = Client(slow_mode=True)
    client.run()
Пример #14
0
def run():
    config = ConfigParser.ConfigParser()
    with open(CONFIG_PATH) as config_fp:
        config.readfp(config_fp)
    logging.config.dictConfig(LOGGING_CONFIG)
    client = Client(config)
    client.start()
Пример #15
0
def get_user_input():
    url = request.form.get('url')
    is_private_mode = 0
    if request.form.get('private'):
        is_private_mode = 1
    if "proxy-settings" in url:
        return proxy_settings()
    data = {'url': url, 'is_private_mode': is_private_mode}
    client = Client()
    client.run(data)
    response = client.response_from_proxy()
    body = response[0]
    now = datetime.datetime.today().strftime("%Y%m%d-%H%M%S")
    # name_of_file = random.randint(1000, 10000)
    filename = '/Users/thomasyyu/Documents/GitHub/CSC645/csc645-01-fall2019-projects-thomasyyyu/applications/web-server-proxy/templates/'
    filename = filename + 'index' + '.html'
    f = open(filename, 'w')
    wrapper = """<!DOCTYPE html>
        <html>
            <head>
                <title>%s output - %s</title>
            </head>
            <body>
                <form>
                    <input type="button" value="Go back!" onclick="history.back()">
                </form>
                <p>URL: <a href=\"%s\">%s</a></p><p>%s</p></body>
        </html>"""
    whole = wrapper % (url, now, url, url, body)
    f.write(whole)
    f.close()
    return render_template("index.html")
Пример #16
0
def main():
    client = Client()
    try:
        client.start()
    except (KeyboardInterrupt, IOError):
        print('[INFO] Exit now...')
        return
Пример #17
0
def download(path_from, path_to):
    """Download a file"""
    cl = Client()
    res = cl.download_file(path_from, path_to)
    # print(res)
    stat = res['status']
    if stat != Status.ok:
        print(Status.description(stat))
Пример #18
0
def main():
    args = sys.argv[1:]
    print("-" * 20)
    print("fetching data for :", args)
    c = Client()
    fut = c.call_reddit(args)
    c.complete_loop_now(fut)
    print("-" * 20)
Пример #19
0
 def get_all_clients(self):
     directory_answers = os.getcwd() + "/answers"
     for file in os.listdir(directory_answers):
         if file.endswith(".py"):
             filename = os.fsdecode(file)
             name = filename.split(".")[0]
             mod = importlib.import_module("answers." + name, __name__)
             client_new = Client(name, mod.answer_rfq)
             self.clients.append(client_new)
Пример #20
0
def main():
    parser = argparse.ArgumentParser('Telegram client')
    parser.add_argument('--host', type=str, default='localhost')
    parser.add_argument('--port', type=int, default=9876)
    parser.add_argument('msg', type=str, help='msg to send')
    args = parser.parse_args()

    client = Client(args.host, args.port)
    client.send(args.msg)
def main():
    storage = BasicFileSystemStorage(STORAGE_PARENT, use_datetime=True)
    with StubCamera() as camera, \
            UdpConnection.create(CLIENT_PORT, SERVER_ADDRESS) as conn:
        client = Client(conn, storage, camera)

        print('Starting')
        while True:
            client.handle_next_command()
Пример #22
0
    def test_init(self, mStdout):
        mSocket = mock.Mock()
        mDbc = mock.Mock()

        Client(mSocket, mDbc)

        mStdout.assert_has_calls(
            [mock.call.write("[+] Client connected"),
             mock.call.write('\n')])
Пример #23
0
def nodeless_client():
    """
        A client that is suited for being used in tests that do not
        require a node
    """
    client_path = _wrap_path(CLIENT)
    client_admin_path = _wrap_path(CLIENT_ADMIN)
    client = Client(client_path, client_admin_path, endpoint=None)
    yield client
    client.cleanup()
Пример #24
0
def run(host, port, name):
    game = Game(name)
    client = Client(game)

    def on_connected(protocol):
        protocol.callback = lambda msg: client.handle(msg)
        client.conn = protocol
        client.run()
        gameloop(game, client)

    netclient.connect(host, port, on_connected)
Пример #25
0
def upload(local_path, remote_path):
    """Create a file"""
    cl = Client()

    if os.path.isdir(local_path):
        print("You can't upload directory as a file")
    else:
        res = cl.create_file(local_path, remote_path)
        stat = res['status']
        if stat != Status.ok:
            print(Status.description(stat))
Пример #26
0
def tezos_client():
    # TODO use one client per session, clean-up client resources
    client = Client(CLIENT,
                    CLIENT_ADMIN,
                    host=HOST,
                    rpc_port=PORT,
                    use_tls=False)

    identities = constants.IDENTITIES
    client.import_secret_key('bootstrap1', identities['bootstrap1']['secret'])
    return client
Пример #27
0
    def test_parseNetworkObject_errorUnknown(self, mSocket, mDbc, mNo, mPrint):
        mDbc.execute.return_value = {"error": "Error unknown", "result": ""}
        client = Client(mSocket, mDbc)

        no = client.parseNetworkObject(mNo)

        self.assertEqual(no.error, "Error unknown")
        self.assertEqual(no.command, "no command")
        self.assertEqual(no.table, "no table")
        self.assertEqual(no.key, "")
        self.assertEqual(no.payload, {})
Пример #28
0
def get_user_input():
    url = request.form.get('url')
    is_private_mode = 0
    if request.form.get('private'):
        is_private_mode = 1
    if "proxy-settings" in url:
        return proxy_settings()
    data = {'url': url, 'is_private_mode': is_private_mode}
    new_client = Client(data)
    #new_client.response_from_proxy()

    return str(data)
Пример #29
0
def main():
    """
    Run the server
    :return:
    """
    client = Client()

    def signal_handler(signal, frame):
        sys.exit(0)

    signal.signal(signal.SIGINT, signal_handler)
    client.run()
Пример #30
0
 def __init__(self, chain_id=0, peers=[], ip="n/a"):
     self.mining_paused = False
     self.transactions_pool = ListDict()
     self.chain = ListDict()
     self.chain_id = chain_id
     self.node_ip = ip
     self.client = Client()
     self.peers = peers
     self.block_limit = BLOCK_LIMIT
     self.nounce_distance = NOUNCE_DISTANCE
     self.create_genesis_block()
     self.total_num_transactions_generated = 0
     log_info("[node.blockchain.Blockchain.__init__] Blockchain created")