2016-11-23 76 views
0

我是python的新手,我想製作一個程序將命令發送到2960思科交換機並顯示回結果。Python 3 telnetlib「需要類似字節的對象」

我能夠與交換機建立連接並讓它顯示我的橫幅信息,但是一旦我嘗試輸入用戶名和密碼,一切就會順利進行。以下是錯誤消息我得到:

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

The Python 3 telnetlib documentation是關於要「字節串」非常明確的。常規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: ") 

...等等。

相關問題