我有这个脚本:
#!/usr/bin/env python
#import needed modules
import telnetlib
import time
#define variables
HOST = "xxxxxx"
user = "xxxxxx"
password = "xxxxxx"
#open telnet connection
tn = telnetlib.Telnet(HOST, 10800)
time.sleep(2)
#check for initial screen and press enter to go to login
tn.read_until("Device")
tn.write("\r\n")
time.sleep(2)
#Wait for username prompt and enter user/pass
try:
tn.read_until("User Name:",5)
except:
#Timeout looking for Username prompt
print "CRITICAL: User Name prompt never arrived"
exit(2)
tn.write(user + "\r\n")
tn.read_until("Password :")
tn.write(password + "\r\n")
time.sleep(2)
#wait for logout prompt
try:
tn.read_until("7<Logout >",5)
except:
#Timeout looking for successful login
print "CRITICAL: Did not login successfully"
exit(2)
#Logout and close connection
tn.write("7\r")
tn.close()
#Exit with success
print "OK: Test login to MWA Succeeded"
exit(0)
无论我做什么,都没有例外。我更改了read_until,寻找&#34;用户名:&#34;只是一些垃圾字符,它仍然只是到达代码的末尾。我希望我只是做一些非常愚蠢的事情,而不是telnetlib的问题。
谢谢!
答案 0 :(得分:2)
读取,直到遇到预期的给定字符串或直到超时 几秒钟过去了。
如果找不到匹配项,可能会返回可用的内容 空字符串。如果连接已关闭且没有,则引发EOFError 熟食数据可用。
检查try
块中的返回值,如果此值与您的预期不符,则raise
会自行触发except
个案。