Python 没有捕获异常
Python not catching exceptions
我有这个脚本:
#!/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)
无论我做什么,都没有发现异常。我将寻找 "User Name:" 的 read_until 更改为一些垃圾字符,它仍然只是到达代码的末尾。我希望我只是在做一些非常愚蠢的事情,而不是 telnetlib 的问题。
谢谢!
Read until a given string, expected, is encountered or until timeout
seconds have passed.
When no match is found, return whatever is available instead, possibly
the empty string. Raise EOFError if the connection is closed and no
cooked data is available.
检查try
块中的return值,如果这个值不符合您的预期,raise
自行触发except
情况。
我有这个脚本:
#!/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)
无论我做什么,都没有发现异常。我将寻找 "User Name:" 的 read_until 更改为一些垃圾字符,它仍然只是到达代码的末尾。我希望我只是在做一些非常愚蠢的事情,而不是 telnetlib 的问题。
谢谢!
Read until a given string, expected, is encountered or until timeout seconds have passed.
When no match is found, return whatever is available instead, possibly the empty string. Raise EOFError if the connection is closed and no cooked data is available.
检查try
块中的return值,如果这个值不符合您的预期,raise
自行触发except
情况。