Python 3 telnetlib"类似字节的对象是必需的"

时间:2016-11-23 16:37:36

标签: python

我是python的新手,我想创建一个程序,将命令发送到2960思科交换机并让它显示结果。

我能够连接到交换机并让它显示我的横幅消息,但是一旦我尝试输入我的用户名和密码,一切都会下降。这是我收到的错误消息:

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)$

1 个答案:

答案 0 :(得分:2)

The Python 3 telnetlib documentation非常明确地想要&#34;字节字符串&#34;。常规Python 3字符串是多字节字符串,没有附加显式编码;制作它们的字节字符串意味着将它们向下渲染,或者将它们生成为预渲染的字节串文字。

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

'foo'.encode('utf-8') # using UTF-8; replace w/ the encoding expected by the remote device
如果您对源代码使用的编码与远程设备所期望的编码兼容(就常量字符串中包含的字符而言),请将

指定为字节字符串文字:

b'foo'

因此:

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

...等