我有使用 telnet 并且需要登录的代码。如果登录不正确,则向控制台返回“登录不正确”。我想捕捉这个异常并跳过它,这样它就不会停止程序。我试过的如下:
try:
session.write("username".encode('ascii') + b"\r")
session.write("password".encode('ascii') + b"\r")
***this is the point where the console will return "Incorrect login"***
except sys.stdout == "Incorrect login":
print(sys.stdout)
pass
else:
**Rest of the code**
似乎它永远不会捕获此输出,继续执行我的代码并最终导致索引错误(因为我没有登录所需的数据)。我尝试搜索但没有运气。任何帮助,将不胜感激。我正在运行 python 3.3,并且仍在学习。谢谢!
编辑:这是 telnet 显示的内容
login: badusername
password: **blank b/c it is a pw field**
Login incorrect
login:
Edit2:所有代码到 else (为保密而编辑)
import telnetlib, time
import sys, string, socket
import cx_Oracle
sql = "select column from table"
con = cx_Oracle.connect("login info blah...")
cur = con.cursor()
cur.execute(sql)
row = cur.fetchone()
rows = cur.fetchall()
def Tup():
return (rows)
cur.close()
con.close()
i = 0
while i < len(rows):
host = Tup()[i][0]
timeout = 120
print(host + ' =', end = ' ')
try:
session = telnetlib.Telnet(host, 23, timeout)
except:
out = open("Data.txt",'a')
out.write(host + " = FAILED\n")
print("FAILED")
else:
try:
session.write("username".encode('ascii') + b"\r")
session.write("pass".encode('ascii') + b"\r")
except sys.stdout == "Incorrect login":
print(sys.stdout)
pass
else: