简体   繁体   中英

Python not catching exceptions

I have this script:

#!/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)

No matter what I do, no exceptions are caught. I changed the read_until looking for "User Name:" to just some garbage characters and it still just gets to the end of the code. I'm hoping I'm just doing something very stupid and not an issue with telnetlib.

Thanks!

Per the docs :

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.

Check the return value in the try block, and if this value does not match your expectations, raise on your own to trigger the except case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM