TypeError: 'in <string> while 通过 python telnet 发送 cmd

问题描述

我尝试通过 python telnet 发送 ls / cmd

import telnetlib
tel = telnetlib.Telnet('10.10.0.1'.'1234')
tel.write('ls / ')

但是我遇到了一个错误

if IAC in buffer:
TypeError: 'in <string>' requires string as left operand,not bytes

解决方法

您需要将字符串编码为 ASCII:

tel.write(('ls / ').encode('ascii'))

在 Python3 中,str 类将字符串存储为 unicode,您需要将它们显式转换为 ascii。您基本上需要一个字节字符串,其中每个字符都作为 ASCII 字符而不是 Unicode 字符。