[英]How to fix: UnicodeDecodeError: 'utf-8' codec can't decode byte 0x81 in position 18: invalid start byte
I am trying to make a remote shell, using sockets. Some commands are working like netstat
or dir
.我正在尝试使用 sockets 制作远程 shell。一些命令的工作方式类似于
netstat
或dir
。 But when I try to use a ping
, this error message comes up:但是当我尝试使用
ping
时,会出现此错误消息:
This problem only occurs on the server side, if I try to encode the message in utf-8. With a normal byte string it works fine.如果我尝试对 utf-8 中的消息进行编码,则此问题仅发生在服务器端。使用普通字节字符串,它工作正常。 I have also tried to receive first and then encode the string.
我也试过先接收然后编码字符串。
Server side:服务器端:
while True:
cmd = input(">>>")
if len(str.encode(cmd)) > 0:
connection.send(str.encode(cmd))
client_response = str(connection.recv(1024), encoding = "utf-8")
print (client_response, end = "")
Client side:客户端:
while True:
data = sock.recv(1024).decode("utf-8")
proc = subprocess.Popen(shlex.split(data),
shell = True,
stdin = subprocess.PIPE,
stdout = subprocess.PIPE,
stderr = subprocess.PIPE)
output = proc.stdout.read()+proc.stderr.read()
sock.send(output)
Maybe someone could give me a tip.也许有人可以给我提示。
As an aside, I think your client and server definitions may be the wrong way around.
顺便说一句,我认为您的客户端和服务器定义可能是错误的。 The client should be the one accepting user input and sending that off to the server for execution.
客户端应该是接受用户输入并将其发送到服务器执行的那个。 However, that's not really relevant to your question.
但是,这与您的问题并不相关。
I will, however, refer to them as user side (where user inputs commands) and execution side (where the process is run) to hopefully avoid misunderstanding.
但是,我将它们称为用户端(用户输入命令的地方)和执行端(进程运行的地方),希望能避免误解。
I see that no encoding is done to the output on the execution side of the link, you simply return the standard output and error as-is.我看到在链接的执行端没有对 output 进行任何编码,您只需按原样返回标准 output 和错误。
I'd suggest printing that out before sending so you can see what it contains, as well as printing it out before attempting conversion on the user side:我建议在发送之前将其打印出来,以便您可以查看其中包含的内容,并在尝试在用户端进行转换之前将其打印出来:
# On exection side:
output = proc.stdout.read()+proc.stderr.read()
print('before send', output)
# On user side:
client_response = connection.recv(1024)
print('got response', client_response)
client_response = str(client_response, encoding = "utf-8")
The start byte 0x81
is very much invalid as a UTF-8 start byte - it should either have the leftmost bit set to zero or the leftmost two bits set to one.起始字节
0x81
作为 UTF-8 起始字节非常无效 - 它应该将最左边的位设置为零或将最左边的两位设置为 1。 0x81
is binary 1000 0001
so does not meet that requirement. 0x81
是二进制1000 0001
因此不符合该要求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.