RTU/mimo/webserver测试工程师/test_debug_dc.py

112 lines
3.2 KiB
Python

#!/usr/bin/env python3
"""调试 datacenter out 命令"""
import socket, base64, os, struct, json, time
IP = '198.120.0.100'; PORT = 8000
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(10)
sock.connect((IP, PORT))
key = base64.b64encode(os.urandom(16)).decode()
req = (f"GET /ws HTTP/1.1\r\nHost: {IP}:{PORT}\r\nUpgrade: websocket\r\n"
f"Connection: Upgrade\r\nSec-WebSocket-Key: {key}\r\n"
f"Sec-WebSocket-Version: 13\r\n\r\n")
sock.sendall(req.encode())
resp = b""
while b"\r\n\r\n" not in resp:
resp += sock.recv(4096)
print(f"[✓] 握手: {resp.split(b'\r\n')[0].decode()}")
# 先收 cmd_list
time.sleep(0.5)
sock.settimeout(1.0)
all_data = b""
try:
while True:
c = sock.recv(65536)
if not c: break
all_data += c
except socket.timeout:
pass
print(f"[i] 初始数据: {len(all_data)} 字节")
# 发送 get_cmds
msg = json.dumps({"type": "get_cmds"})
L = len(msg.encode())
mask = os.urandom(4)
payload = msg.encode()
masked = bytes(payload[i] ^ mask[i % 4] for i in range(L))
frame = bytearray([0x81, 0x80 | L])
frame.extend(mask); frame.extend(masked)
sock.sendall(bytes(frame))
print(f"[→] get_cmds")
time.sleep(0.5)
# 收 cmd_list
all_data = b""
try:
while True:
c = sock.recv(65536)
if not c: break
all_data += c
except socket.timeout:
pass
print(f"[i] get_cmds 响应: {len(all_data)} 字节")
if all_data:
# 跳过 2 字节 WS 头
if len(all_data) > 2:
L2 = all_data[1] & 0x7F
print(f" 帧长度={L2}, payload={all_data[2:2+L2].decode(errors='replace')[:500]}")
# 现在测试 datacenter out
cmd = json.dumps({"type": "cmd", "cmd": "datacenter out"})
payload = cmd.encode()
L = len(payload)
mask = os.urandom(4)
masked = bytes(payload[i] ^ mask[i % 4] for i in range(L))
frame = bytearray([0x81, 0x80 | L])
frame.extend(mask); frame.extend(masked)
sock.sendall(bytes(frame))
print(f"[→] datacenter out")
time.sleep(2.0)
# 收响应
all_data = b""
try:
while True:
c = sock.recv(65536)
if not c: break
all_data += c
print(f"[i] 收到 {len(c)} 字节")
except socket.timeout:
print(f"[i] 超时,共 {len(all_data)} 字节")
print(f"\n总响应: {len(all_data)} 字节")
if len(all_data) == 0:
print("[✗] datacenter out 无响应!可能命令不存在或执行失败")
else:
# 解析所有帧
offset = 0
while offset + 2 <= len(all_data):
b0, b1 = all_data[offset], all_data[offset+1]
opcode = b0 & 0x0F
length = b1 & 0x7F
offset += 2
if length == 126:
length = struct.unpack('>H', all_data[offset:offset+2])[0]; offset += 2
elif length == 127:
length = struct.unpack('>Q', all_data[offset:offset+8])[0]; offset += 8
p = all_data[offset:offset+length]; offset += length
try:
j = json.loads(p.decode('utf-8'))
print(f" [{opcode}] JSON: type={j.get('type','?')}")
if j.get('type') == 'dc_data':
for k in ['out','in','yk','ao','param']:
print(f" {k}: {len(j.get(k,[]))} 个信号")
except:
txt = p.decode('utf-8', errors='replace')
print(f" [{opcode}] {txt[:300]}")
sock.close()