def week_number_valid(module_code, week_number, s: socket.socket):
    s.sendall(b"Checking Assignment Week")
    if s.recv(1024).decode() == "OK":
        s.sendall(module_code.encode())
        s.sendall(week_number.encode())
        result = s.recv(1024).decode()
        if result == "True":
            return True
    return False
示例#2
0
def echo_client1(sock: socket, client_addr):
    print("Got connection from ", client_addr)
    while True:
        msg = sock.recv(65536)
        if not msg:
            break
        sock.sendall(msg)
    print("Client closed connection")
    sock.close()
示例#3
0
def send_dict(sock: socket.socket, dict_to_send: Dict) -> None:
    """
    发送一个字典
    :param sock:
    :param dict_to_send:
    :return:
    """
    content = (json.dumps(dict_to_send) + 'PMEND').encode('utf-8')
    sock.sendall(content)
示例#4
0
def send(sock: socket.socket, success: bool, end: bool, data: bytes):
    head = struct.pack("!H??", len(data), success, end)
    while True:
        try:
            sock.sendall(head + data)
        except BlockingIOError:
            #系统尚未准备好发送
            continue
        else:
            break
示例#5
0
def handshake_server(conn: socket.socket):
    recipient_key = RSA.import_key(recvall(conn))
    session_key = get_random_bytes(32)

    cipher_rsa = PKCS1_OAEP.new(recipient_key)
    enc_session_key = cipher_rsa.encrypt(session_key)
    cipher_aes = AES.new(session_key, AES.MODE_GCM)
    nonce = cipher_aes.nonce
    conn.sendall(enc_session_key + nonce)
    return (session_key, nonce)
示例#6
0
 def _send_listening_fd(self, target_sock: socket.socket):
     pid_buffer = bytearray()
     while len(pid_buffer) < dword.size:
         recvd = target_sock.recv(dword.size - len(pid_buffer))
         if not recvd:
             return
         pid_buffer += recvd
     target_pid, = dword.unpack(pid_buffer)
     handle_bytes = self._socket.share(target_pid)
     target_sock.sendall(bytes(len(handle_bytes), ) + handle_bytes)
示例#7
0
def cmd_send_reload_to_time_manager(wiser_elf: wiserelf.WiserElf,
                                    conn: socket.socket) -> None:
    """
    cmd send reload to time_manager process queue, put tuple ("policy_reset", None) to process queue
    :param wiser_elf: wiser elf class var
    :param conn: socket connect
    """
    wiser_elf.get_process_fifo_args()["->[TimeManager]"].put(
        ("policy_reset", None))
    conn.sendall(wiser_elf.send_last_msg("Set Reload Flag Ok.").encode())
示例#8
0
def client_handler(sock: socket.socket):
    _ = sock.recv(1024)
    time.sleep(0.3)
    sock.sendall(
        b"HTTP/1.1 200 OK\r\n"
        b"Content-Type: text/html\r\n"
        b"Content-Length: 71\r\n\r\n"
        b"<html><head><title>Success</title></head><body>Index page</body></html>"
    )
    sock.close()
示例#9
0
def send_dashmips_message(client: socket, data: str):
    r"""Send a dashmips debugger message.

    Size is calculated from the utf8 encoding of data.
    """
    data_encoded = bytes(data, "utf8")
    size = len(data_encoded)
    size_header = bytes(json.dumps({"size": size}), "utf8")
    out_message = size_header + data_encoded
    client.sendall(out_message)
示例#10
0
def handle_log_query(s: socket, p: Petition):
    """
    Simply logs the request and returns OK
    """
    data = "OK".encode()

    print(f"[i] Got {p.header_map}")

    resp = craft_response("200 OK", "text/plain", data)
    s.sendall(resp)
示例#11
0
 def _send_and_recv(conn: socket.socket, data: str) -> str:
     conn.sendall(data.encode())
     result = ""
     while True:
         received = conn.recv(1024)
         if received == b"":
             break
         else:
             result += received.decode('utf-8', errors='ignore')
     return result
示例#12
0
def rpc(sock: socket.socket, in_, params):
    request = json.dumps({"in": in_, "params": params})  # 请求消息体
    length_prefix = struct.pack("I", len(request))  # 请求长度前缀
    sock.send(length_prefix)
    sock.sendall(request.encode())  # sendall = send + flush
    length_prefix = sock.recv(4)  # 响应长度前缀
    (length, ) = struct.unpack("I", length_prefix)
    body = sock.recv(length).decode()  # 响应消息体
    response = json.loads(body)
    return response["out"], response["result"]  # 返回响应类型和结果
示例#13
0
    def send_output(sock: socket.socket, msg: str, out_type: str) -> None:
        """Prefix/send messages with 32-bit unsigned int size prefix. This
        method is intended to be used by Client to send command output"""
        if out_type in ["output", "error"]:
            msg = "::".join([out_type, msg])
        else:
            raise ValueError("Expected <out_type> to be in [output|error]")

        message = struct.pack(">I", len(msg)) + msg.encode()
        sock.sendall(message)
示例#14
0
def server_input_handler(client: socket.socket, execute: bool=False):
    while True:
        try:
            data = client.recv(4096).decode()
            if execute:
                data = execute_command(data)
                client.sendall(data)
            print(data, end='')
        except Exception as err:
            pass
示例#15
0
 def serve_client(self, client_sock: socket.socket):
     client_sock.settimeout(TIMEOUT)
     while True:
         data = client_sock.recv(1024)
         if data == b"":
             client_sock.shutdown(1)
             client_sock.close()
             break
         if data:
             client_sock.sendall(data)
def send_image(connection: socket.socket, image: np.ndarray):
    with BytesIO() as fp:
        # Disable pickle for security, cf https://numpy.org/doc/stable/reference/generated/numpy.load.html
        np.save(fp, image, allow_pickle=False)
        fp.flush()
        content = fp.getvalue()
    filesize = len(content)
    content = filesize.to_bytes(BUFSIZE, "big") + content
    connection.sendall(content)
    print(f"{now().strftime('%H:%M:%S,%f')} - Sent {filesize} bytes.")
示例#17
0
def _handle_request(connection: socket.socket, addr: tuple, hdir: str,
                    shdir: str):
    req = pickle.loads(connection.recv(1000))
    if req[0] == "get":
        print(f'{addr} requested to get "{req[1]}"')
        try:
            data = open(os.path.join(hdir, req[1].replace("/", os.sep)),
                        "r+b").read()
            d = bdtp.new_send_data_host(data, ("", 0))
            d.send(connection)
        except Exception as e:
            print(f"{addr} get request failed: {str(e)}")
    elif req[0] == "typelistdir":
        print(f'{addr} requested to typelistdir "{req[1]}"')
        try:
            d = os.listdir(os.path.join(hdir, req[1].replace("/", os.sep)))
            s = [(
                x,
                0 if os.path.isdir(
                    os.path.join(hdir, req[1].replace("/", os.sep), x)) else 1,
            ) for x in d]
            r = pickle.dumps(s)
            d = bdtp.new_send_data_host(r, ("", 0))
            d.send(connection)
        except Exception as e:
            print(f"{addr} typelistdir request failed: {str(e)}")
    elif req[0] == "mkdir":
        print(f'{addr} requested to mkdir "{req[1]}"')
        try:
            os.mkdir(os.path.join(hdir, req[1].replace("/", os.sep)))
        except Exception as e:
            print(f"{addr} mkdir request failed: {str(e)}")
    elif req[0] == "listdir":
        print(f'{addr} requested to listdir "{req[1]}"')
        try:
            r = pickle.dumps(
                os.listdir(os.path.join(hdir, req[1].replace("/", os.sep))))
            d = bdtp.new_send_data_host(r, ("", 0))
            d.send(connection)
        except Exception as e:
            print(f"{addr} listdir request failed: {str(e)}")
    elif req[0] == "post":
        print(f'{addr} requested to post "{req[1]}"')
        try:
            connection.sendall(b" ")
            d = bdtp.new_receive_data_host(("", 0))
            d.recv(connection)
            f = open(os.path.join(hdir, shdir, req[1].replace("/", os.sep)),
                     "w+b")
            f.write(d.data)
            f.close()
            print(f"{addr} post request successful")
        except Exception as e:
            print(f"{addr} post request failed: {str(e)}")
    connection.close()
示例#18
0
 def handle_packet(self, client: socket.socket, packet: bytes):
     try:
         dic = json.loads(packet)
         func = self.server.dispatcher_dic[dic['method']]
         args = dic['params']
         client.sendall(func(*args).encode('utf-8') + b'PMEND')
     except:
         client.close()
         self.signal_socket_closed.emit(client)
         logger.warning(repr(self.server.long_conn_sockets))
         return b''
示例#19
0
def authenticate(connexion_to_server: socket.socket) -> tuple[str, RSAPublicKey]:
    username = input("username ?> ")
    payload = b"\n".join([username.encode(), serial_public_key])
    connexion_to_server.sendall(payload)
    response = connexion_to_server.recv(BUFFER_SIZE)
    if response == ResponseCode.USERNAME_ALREADY_EXISTS:
        raise AuthenticationError(f"The username {username} is already taken")
    elif response == ResponseCode.USERNAME_DOES_NOT_EXIST:
        raise AuthenticationError("This username does not exist. Add your public key to the payload to create it.")
    else:
        return username, load_public_key(response)
def get_exec_result(module_code, week_number, student_id, s: socket.socket, file_suffix, penalty: str) -> str:
    s.sendall(b"Get exec result")
    if s.recv(1024).decode() == "OK":
        s.sendall(module_code.encode())
        s.sendall(week_number.encode())
        s.sendall(student_id.encode())
        s.sendall(file_suffix.encode())
        s.sendall(penalty.encode())

        result = s.recv(1024).decode()
        return result
示例#21
0
    def _handle(self, connection: socket.socket):
        while True:
            command = connection.recv(1024).decode("utf-8")

            if not command:
                raise RuntimeWarning("Empty command")

            response = self.hardware.get(command=command)

            connection.sendall(response.encode("utf-8"))
            logger.info("{} {}".format(command, response))
示例#22
0
def send_request(soc: socket.socket, param: bytes) -> None:
    """ Higher level call to send data to socket

    :param soc: The socket to send data to
    :param param: The bytes to send
    :return: None
    """
    try:
        soc.sendall(struct.pack("I", len(param)) + param)
    except OSError:
        pass
 def _receive_and_send_data_to_client(server_connection: socket.socket,
                                      client_connection: socket.socket):
     while True:
         try:
             data = server_connection.recv(MAX_REQUEST_LEN)
             if len(data) > 0:
                 client_connection.sendall(data)
             else:
                 break
         except socket.timeout:
             break
示例#24
0
def send_message(sock: socket.socket, message: str):
    # pretvori sporocilo v niz bajtov, uporabi UTF-8 kodno tabelo
    encoded_message = message.encode("utf-8")

    # ustvari glavo v prvih 2 bytih je dolzina sporocila (HEADER_LENGTH)
    # metoda pack "!H" : !=network byte order, H=unsigned short
    header = struct.pack("!H", len(encoded_message))

    # najprj posljemo dolzino sporocilo, slee nato sporocilo samo
    message = header + encoded_message
    sock.sendall(message)
示例#25
0
def ping_node(ip: str, port: int, socket_obj: socket.socket):
    """
    Utility function.
    Sends ping to a render node's socket.
    """
    data = b""
    socket_obj.connect((ip, port))
    socket_obj.sendall(b"PING")
    data = socket_obj.recv(1024)
    socket_obj.close()
    return data == b"PONG"
示例#26
0
def send_command(sock: socket.socket, command_dict: dict):
    msg = struct.pack('<BB', 3, len(command_dict))
    for frameId, command in command_dict.items():
        command = command.encode('ascii')
        msg += struct.pack('<ii{}s'.format(len(command)), frameId, len(command), command)

    msg = struct.pack('<i', len(msg)) + msg
    try:
        sock.sendall(msg)
    except:
        print("Failed to send commands")
示例#27
0
文件: pop3.py 项目: vaspahomov/pop3
def send(sock: socket.socket, command):
    sock.sendall(f'{command}\n'.encode())
    sock.settimeout(0.5)
    res = ''
    try:
        mess = sock.recv(BUFFER_SIZE).decode()
        while mess:
            res += mess
            mess = sock.recv(BUFFER_SIZE).decode()
    finally:
        return res
示例#28
0
    def send_msg(self, s: socket, msg: str):
        """Sends msg as utf-8 encoded bytes to self.name_server.
        (If sendall() fails on the background of lost connection,
        it tries to reconect)

        Args:
            msg (str): msg to encode and send
        """
        try:
            s.sendall(bytes(msg + GC.END_MARKER, GC.ENCODING))
        except Exception as e:
            print(">> Could not send message: ", e)
示例#29
0
def handle_client(client_sock: socket.socket):
    # Read header
    header_buf = b""
    payload_buf = b""

    with client_sock:
        while True:
            tmp = client_sock.recv(BUF_SIZE)
            if not tmp:
                break

            header_buf += tmp
            i = header_buf.rfind(b"\r\n\r\n")
            if i != -1:
                header_buf = header_buf[:i]
                payload_buf += header_buf[i:]
                break

        header = Header.from_raw(header_buf)

        if header.http_path.endswith(".htm") or header.http_path.endswith(
                ".html"):
            # Check if path exists
            path = filepath / Path(header.http_path[1:])
            print(path)
            if path.exists():
                print("File exists, trying to send file")
                # file exists, send file
                client_sock.sendall(
                    RESP_HEADER_TMPL.format(code=200,
                                            msg=HTTP_MSG[200],
                                            length=path.stat().st_size,
                                            content_type="text/html").encode())
                send_file_to_sock(client_sock, path)
            else:
                # file doesn't exist
                print("File doesnt exist, sending error msg")
                client_sock.sendall(
                    RESP_HEADER_TMPL.format(code=403,
                                            msg=HTTP_MSG[403],
                                            length=len(HTTP_ERROR_TMPL),
                                            content_type="text/html").encode())
                client_sock.sendall(HTTP_ERROR_TMPL)

        else:
            # Not asking for a HTML file, we don't know how to handle that
            print("Not asking for html, abort")
            client_sock.sendall(
                RESP_HEADER_TMPL.format(code=404,
                                        msg=HTTP_MSG[404],
                                        length=len(HTTP_ERROR_TMPL),
                                        content_type="text/html").encode())
            client_sock.sendall(HTTP_ERROR_TMPL)
示例#30
0
def sendCurrentvalue(sock: socket.socket, bound: int):
    global V, lowBound, highBound, myName

    V = h1 * dtCPU + h2 * dtRAM + h3 * dtMEM

    if (V > bound):
        dataSend = createMessage('',
                                 {'-type': MyEnum.MonNode.NODE_SET_DATA.value})
        dataSend = createMessage(dataSend, {'-ses': session})
        dataSend = createMessage(dataSend, {'-value': V})
        sock.sendall(bytes(dataSend.encode()))
        print('send')
示例#31
0
 def send_data(self, data, sock: socket.socket) -> str:
     try:
         sock.sendall(data)
         return ""
     except Exception as e:
         return str(e)
示例#32
0
def send(sock: socket.socket, message: bytes):
    """Pack the message length and content for sending larger messages."""
    message = struct.pack('>I', len(message)) + message
    sock.sendall(message)
def socket_sendall(sock: socket.socket, data: str) -> None:
    # return socket.sendall(data)  # Python 2
    return sock.sendall(data.encode("ascii"))  # Python 3