Python 实现WebSocket通信(python培训)

网友投稿 459 2022-09-02


Python 实现WebSocket通信(python培训)

import socket,struct,hashlib,base64def get_headers(data): headers = {} data = str(data, encoding="utf-8") header, body = data.split("\r\n\r\n", 1) header_list = header.split("\r\n") for i in header_list: i_list = i.split(":", 1) if len(i_list) >= 2: headers[i_list[0]] = "".join(i_list[1::]).strip() else: i_list = i.split(" ", 1) if i_list and len(i_list) == 2: headers["method"] = i_list[0] headers["protocol"] = i_list[1] return headersdef parse_payload(payload): payload_len = payload[1] & 127 if payload_len == 126: mask = payload[4:8] decoded = payload[8:] elif payload_len == 127: mask = payload[10:14] decoded = payload[14:] else: mask = payload[2:6] decoded = payload[6:] bytes_list = bytearray() for i in range(len(decoded)): chunk = decoded[i] ^ mask[i % 4] bytes_list.append(chunk) body = str(bytes_list, encoding='utf-8') return bodydef send_msg(conn, msg_bytes): token = b"\x81" length = len(msg_bytes) if length < 126: token += struct.pack("B", length) elif length <= 0xFFFF: token += struct.pack("!BH", 126, length) else: token += struct.pack("!BQ", 127, length) msg = token + msg_bytes conn.sendall(msg) return Truedef recv_msg(conn): recv = conn.recv(8096) ref_string = parse_payload(recv) return ref_stringif __name__ == "__main__": sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(("127.0.0.1", 10083)) sock.listen(5) conn, addr = sock.accept() data = conn.recv(8096) headers = get_headers(data) # 对请求头中的sec-websocket-key进行加密 response_tpl = "HTTP/1.1 101 Switching Protocols\r\n" \ "Upgrade:websocket\r\n" \ "Connection: Upgrade\r\n" \ "Sec-WebSocket-Accept: %s\r\n" \ "WebSocket-Location: ws://%s\r\n\r\n" magic_string = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11' if headers.get('Sec-WebSocket-Key'): value = headers['Sec-WebSocket-Key'] + magic_string ac = base64.b64encode(hashlib.sha1(value.encode('utf-8')).digest()) response_str = response_tpl % (ac.decode('utf-8'), headers.get("Host")) conn.sendall(bytes(response_str, encoding="utf-8")) while True: print(recv_msg(conn)) send_msg(conn, b"hello lyshark")

多线程

import socket,struct,hashlib,base64import threadingdef get_headers(data): headers = {} data = str(data, encoding="utf-8") header, body = data.split("\r\n\r\n", 1) header_list = header.split("\r\n") for i in header_list: i_list = i.split(":", 1) if len(i_list) >= 2: headers[i_list[0]] = "".join(i_list[1::]).strip() else: i_list = i.split(" ", 1) if i_list and len(i_list) == 2: headers["method"] = i_list[0] headers["protocol"] = i_list[1] return headersdef parse_payload(payload): payload_len = payload[1] & 127 if payload_len == 126: mask = payload[4:8] decoded = payload[8:] elif payload_len == 127: mask = payload[10:14] decoded = payload[14:] else: mask = payload[2:6] decoded = payload[6:] bytes_list = bytearray() for i in range(len(decoded)): chunk = decoded[i] ^ mask[i % 4] bytes_list.append(chunk) body = str(bytes_list, encoding='utf-8') return bodydef send_msg(conn, msg_bytes): first_byte = b"\x81" length = len(msg_bytes) if length < 126: first_byte += struct.pack("B", length) elif length <= 0xFFFF: first_byte += struct.pack("!BH", 126, length) else: first_byte += struct.pack("!BQ", 127, length) msg = first_byte + msg_bytes conn.sendall(msg) return Truedef recv_msg(conn): data_recv = conn.recv(8096) if data_recv[0:1] == b"\x81": data_parse = parse_payload(data_recv) return data_parse return Falsedef handler_accept(sock): while True: conn, addr = sock.accept() data = conn.recv(8096) headers = get_headers(data) response_tpl = "HTTP/1.1 101 Switching Protocols\r\n" \ "Upgrade:websocket\r\n" \ "Connection: Upgrade\r\n" \ "Sec-WebSocket-Accept: %s\r\n" \ "WebSocket-Location: ws://%s\r\n\r\n" magic_string = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11' if headers.get('Sec-WebSocket-Key'): value = headers['Sec-WebSocket-Key'] + magic_string ac = base64.b64encode(hashlib.sha1(value.encode('utf-8')).digest()) response_str = response_tpl % (ac.decode('utf-8'), headers.get("Host")) conn.sendall(bytes(response_str, encoding="utf-8")) t = threading.Thread(target=handler_msg, args=(conn, )) t.start()def handler_msg(conn): with conn as c: while True: try: recv = recv_msg(c) print("接收数据: {}".format(recv)) send_msg(c, bytes("hello lyshark", encoding="utf-8")) except Exception: exit(0)if __name__ == "__main__": sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(("127.0.0.1", 10083)) sock.listen(5) t = threading.Thread(target=handler_accept(sock)) t.start()

前端

改进,监控图形变化:

def handler_msg(conn): with conn as c: while True: try: times = time.strftime("%M:%S", time.localtime()) data = psutil.cpu_percent(interval=None, percpu=True) print("处理时间: {} --> 处理负载: {}".format(times,data)) send_msg(c, bytes(json.dumps({"response":[times,data]}), encoding="utf-8")) time.sleep(60) except Exception: exit(0)if __name__ == "__main__": sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(("127.0.0.1", 10083)) sock.listen(5) t = threading.Thread(target=handler_accept(sock)) t.start()

客户端

实现远程命令执行

后端

def CalculationIP(Addr_Count): ret = [] try: IP_Start = str(Addr_Count.split("-")[0]).split(".") IP_Heads = str(IP_Start[0] + "." + IP_Start[1] + "." + IP_Start[2] +".") IP_Start_Range = int(Addr_Count.split(".")[3].split("-")[0]) IP_End_Range = int(Addr_Count.split("-")[1]) for item in range(IP_Start_Range,IP_End_Range+1): ret.append(IP_Heads+str(item)) return ret except Exception: return 0def handler_msg(conn): with conn as c: while True: try: ref_json = eval(recv_msg(c)) address = ref_json.get("address") command = ref_json.get("command") address_list = CalculationIP(address) for ip in address_list: response = {'addr': ip, 'status': 'success'} print("对主机: {} --> 执行: {}".format(ip,command)) send_msg(c, bytes(json.dumps(response) , encoding="utf-8")) time.sleep(1) except Exception: exit(0)


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Java IO之包装流详解
下一篇:Python通过SNMP监控网络设备(snmp监控交换机)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~