2014-04-22 38 views
0

下面是我的代碼的一個簡單例子,如果你運行,應該重新創建我的問題。我遇到過的一件事情是,如果我的樹莓派(我正在使用teller連接到的東西)被關閉或者網絡電纜被拔掉,則不會出現該錯誤。在python shell中運行telnet時出現錯誤信息

#IMPORTS 
import time 
import telnetlib 
import sys 
import getpass 


#TELNET 
user = input("Please Enter Your Username: ") 
time.sleep(0.4) 
pass_ = input("Please Enter Your Password: ") 

bot = telnetlib.Telnet("192.168.1.128") 
bot.read_until("login: ".encode(), timeout=None) 
bot.write(user + "\n") 
bot.read_until("Password: ".encode(), timeout=None) 
bot.write(pass_ + "\n") 
bot.write("cd PiBits/ServoBlaster") 

我收到以下錯誤信息:

Traceback (most recent call last): 
    File "/Users/kiancross/Desktop/PROJECTS/RASPBERRY_PI/ROBOT/CONTROLLER_GUI/RPi_BOT_CONTROLLER.py", line 17, in <module> 
    bot.write(user + "\n") 
    File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/telnetlib.py", line 289, in write 
    if IAC in buffer: 
TypeError: 'in <string>' requires string as left operand, not bytes 

我運行下面的代碼,你可以在this後看到,但你可以從答案看我改成了上面的代碼,其導致上述錯誤消息。

我應該說,代碼是沒有接近完成的地方,很多東西只是爲了測試,直到我telnet工作!

我已經嘗試了在this帖子中提到的python老版本的修復。

我已經使用print(type(user))來查看變量是什麼類型,它們是字符串。我已嘗試bot.write((user + "\n").encode(latin-1)),如本修復中所示,但仍顯示錯誤消息。我也嘗試過unicode編碼。我知道該行的一部分編碼錯誤,但我不知道它是變量還是"\n"。我曾嘗試做bot.write(user + b"\n"),但是這可以擺脫錯誤。

如果有人有任何其他方法可以阻止此錯誤,我將不勝感激他們。

由於對蟒蛇

P.S進出口運行3.4.0

編輯

我已經試過這樣:

bot = telnetlib.Telnet("192.168.1.128") 
bot.write(user + "\n".encode('ascii')) 
bot.read_until(b"Password: ") 
bot.write((pass_ + "\n").encode('ascii')) 

但我仍然得到同樣的錯誤。

當我這樣做:

bot = telnetlib.Telnet("192.168.1.128") 
bot.read_until(b"login: ") 
bot.write(user + b"\n") 
bot.read_until(b"Password: ") 
bot.write(pass_ + b"\n") 

我得到一個不同的錯誤:

Traceback (most recent call last): 
    File "/Users/kiancross/Desktop/PROJECTS/RASPBERRY_PI/ROBOT/CONTROLLER_GUI/RPi_BOT_CONTROLLER.py", line 23, in <module> 
    bot.write(user + b"\n") 
TypeError: Can't convert 'bytes' object to str implicitly 

所有的錯誤似乎說,它必須是一個字符串,但我的變量都已經字符串。

謝謝

+3

你真的要發佈你這裏的每一個代碼錯誤緩緩通過的人將其固定各個階段的動作?你通過你的代碼?你確切知道錯誤是什麼以及它在哪裏......你得出什麼結論? – Ben

+2

P.S.如果你[刪除問題](http://stackoverflow.com/questions/23220040/error-message-when-running-telnet-in-python-shell),然後按順序重新發布,你最終會提出禁止自己的問題獲得更多關注。有很多建議[這裏](http://meta.stackexchange。如何獲得對你的問題的關注。 – Ben

+0

@Ben我得出的結論是bot.write(用戶+「\ n」)和其他字符串需要更改爲其他字符。例如一個str或字節或類似的東西。但我不確定。如果我列出了所有我嘗試過的東西,那麼它會離開頁面。我搜索了我遇到的錯誤,並發現了這個錯誤:http://mechanix-tips.blogspot.co.uk/2008/12/python-telnetlib-typeerror-in-requires.html但是當嘗試修復早期的python版本,我仍然遇到這個錯誤。如果我已經知道,我不會問這些問題。 – crossboy007

回答

7

遠程登錄界面可能希望以字節而不是Unicode工作。我已經測試了Python3這個代碼,它避免了錯誤:

import telnetlib 
bot = telnetlib.Telnet("127.0.0.1", 22) 
user = "dobbs" 
bot.write((user + "\n").encode('ascii')) 
print(bot.read_all()) 
+0

這沒有奏效。我仍然收到完全相同的錯誤。 – crossboy007

+0

它適合我。請更新您的代碼以顯示您所做的事情。 – poolie

+0

你的問題是你正在將新行編碼爲字節,但是你需要在加入後對整個字符串進行編碼。 – poolie