python - Python3:有没有办法像在 python2 中一样使用 telnetlib,没有 ascii 编码和 b 前缀?
问题描述
有没有办法使用 telnetlib 使 python2 脚本与 python3 兼容?
我注意到我需要在 read_until() 前面加上字母 b,并且当我想 write() 时,我需要在字符串上使用 encode('ascii')。
Python2
tn = telnetlib.Telnet("192.168.1.45")
tn.write("ls " + dirname + "\n")
answer = tn.read_until(":/$")
Python3
tn = telnetlib.Telnet("192.168.1.45")
cmd_str = "ls " + dirname + "\n"
tn.write(cmd_str.encode('ascii'))
answer = tn.read_until(b":/$")
这将帮助我将许多脚本更新到 3.x,因为它是唯一的重大变化。
谢谢!
解决方案
你可以写你自己的子类encodingtelnetlib.py
class Telnet(Telnet):
def __init__(self, host=None, port=0,
timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
encoding='ascii'):
self.encoding = encoding
super().__init__(host, port, timeout)
def write(self, buffer):
if isinstance(buffer, str):
buffer = buffer.encode(self.encoding)
return super().write(buffer)
# and etc.... for other methods
现在它的一个问题是改变import telnetlib
为import encodingtelnetlib as telnetlib
. 这比找到每次读写都容易。
推荐阅读
- javascript - 如何在 multer 上进行多个文件验证
- r - 根据数据框中的 2 个日期消除重复项
- c - 最好的跨平台对齐宏?
- encryption - IBM MARS 密码测试向量
- oracle - Oracle 存储过程无法生成 csv 文件 - ORA-06502: PL/SQL: numeric or value error: string buff
- lua - 我在 1 号鼠标按钮上有一个命令,我希望它在 7 号和 8 号按钮上也能正常工作吗?在我的罗技鼠标上
- python-requests - 如何使用 alpha vantage api 减少请求?
- c# - PhotonView CreatorActorNr、OwnerActorNr 和 ControllerActorNr 的区别
- python - Beautifulsoup with selenium,如何获得第二个文本
- graphql - 接口字段 [field].contentful_id 需要字符串类型!但 [another_field].contentful_id 是字符串类型。使用 Gatsby v3 和 Contentful