Python 3 telnetlib“需要byteslike对象”

2024-05-09 17:47:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,我想做一个程序,发送命令到一个2960cisco交换机,并让它显示结果。

我可以连接到交换机,并让它显示我的横幅信息,但一旦我尝试键入我的用户名和密码,一切都会走下坡路。这是我收到的错误消息:

Traceback (most recent call last):
  File "C:/Users/jb335574/Desktop/PythonLearning/Telnet/TelnetTest2.py", line 8, in <module>
    tn.read_until("Username: ")
  File "C:\Users\admin1\AppData\Local\Programs\Python\Python35-32\lib\telnetlib.py", line 302, in read_until
    i = self.cookedq.find(match)
TypeError: a bytes-like object is required, not 'str'

这是我的代码:

import telnetlib

un = "admin1"
pw = "password123"

tn = telnetlib.Telnet("172.16.1.206", "23")
tn.read_until("Username: ")
tn.write("admin1" + '\r\n')
tn.read_until("Password: ")
tn.write("password123" + '\r\n')
tn.write("show interface status" + '\r\n')

whathappened = tn.read_all()
print(whathappened)$

Tags: inpyreadlineusernameuserstelnettn
1条回答
网友
1楼 · 发布于 2024-05-09 17:47:18

The Python 3 ^{} documentation对于需要“字节字符串”非常明确。常规的Python 3字符串是多字节字符串,没有附加显式编码;要使它们的字节字符串成为字节字符串,意味着要么将它们呈现为向下,要么将它们生成为预先呈现的bytestring文本。


要从常规字符串生成字节字符串,请对其进行编码:

'foo'.encode('utf-8') # using UTF-8; replace w/ the encoding expected by the remote device

或者,如果用于源代码的编码与远程设备期望的编码兼容(就包含在常量字符串中的字符而言),则将其指定为bytestring文本:

b'foo'

因此:

tn.read_until(b"Username: ")
tn.write(b"password1\r\n")
tn.read_until(b"Password: ")

……等等

相关问题 更多 >