如何获得一行控制台返回的内容(字符串)并放入变量中? [英] How do I get a line of the what the console returns (string) and place in a variable?

查看:34
本文介绍了如何获得一行控制台返回的内容(字符串)并放入变量中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有使用 telnet 并需要登录的代码.如果登录不正确,则向控制台返回Incorrect login".我想捕获这个异常并跳过它,这样它就不会停止程序.我尝试的内容如下:

I have code that is using telnet and requires a login. If the login is incorrect, it returns "Incorrect login" to the console. I want to catch this exception and skip it so it doesn't stop the program. What I tried is below:

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 并且仍在学习.谢谢!

It seems that it never catches this output, continues on to my code and ends up in an index error (from not having the data I need from logging in). I tried searching but had no luck. Any help would be appreciated. I'm running python 3.3 and am still learning. Thanks!

这是 telnet 显示的内容

Here is what telnet shows

login: badusername
password: **blank b/c it is a pw field**
Login incorrect

login: 

Edit2:直到 else 的所有代码(为保密而编辑)

All code up to else (edited for confidentiality)

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:

推荐答案

查看 [subprocess][1] 模块,它包含一个返回的 check_output 方法执行命令的输出作为字符串.

Take a look into [subprocess][1] module, it contains a check_output method that returns the output of the executed command as a string.

试试这个.您可能需要更改一些语法细节...

Try this. You might need to change some syntactical details...

PROMPT = '$' # or '#' or '%', the shell prompt
TIMEOUT = 3

try:
    session.read_until(b"login:")
    session.write("username".encode('ascii') + b"\r")

    session.read_until(b"password:")
    session.write("password".encode('ascii') + b"\r")
    login_result = session.read_until(PROMPT, TIMEOUT) # This will make it put whatever is printed till PROMPT into login_result. if it takes more than TIMEOUT seconds, you can assume login failed (since PROMPT never came up)
    ***this is the point where the console will return "Incorrect login"***

    if(login_result[-1] != PROMPT):    # change this -1 to -2 or -3 if the output is trailed by a newline
        raise Exception

except Exception:
    print("Login Failure")
    pass

else:
    **Rest of the code**

这篇关于如何获得一行控制台返回的内容(字符串)并放入变量中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆