telnetlib 类型错误

0 投票
1 回答
2116 浏览
提问于 2025-04-15 20:03

我正在修改一个Python脚本,目的是通过telnet一次性对几个开关进行批量修改:

import getpass
import sys
import telnetlib

HOST = "192.168.1.1"
user = input("Enter your remote account: ")
password = getpass.getpass()

tn = telnetlib.Telnet(HOST)

tn.read_until("User Name: ")
tn.write(user + "\n")
if password:
    tn.read_until("Password: ")
    tn.write(password + "\n")

tn.write("?\n")
tn.write("exit\n")

当脚本运行时,我收到一个错误提示:“TypeError: expected an object with the buffer interface”,如果有人能提供一些帮助就太好了。

1 个回答

2

根据文档read_until的说明是(我强调的部分):

读取直到遇到指定的字节字符串。

在Python 3中,你传入的并不是一个字节字符串,比如:

tn.read_until("User Name: ")

而是传入了一个文本字符串,在Python 3中这意味着一个Unicode字符串。

所以,你需要把它改成

tn.read_until(b"User Name: ")

使用b"..."的形式可以指定一个字面上的字节字符串。

(当然,其他类似的调用也是如此)。

撰写回答