简体   繁体   English

Python,是否可以获取pexpect sendline输出并在其上添加一个条件?

[英]Python, is it possible to take the pexpect sendline output and add a contion on it?

I have a problem that I can't find the answer. 我有一个找不到答案的问题。

I use the Python pexpect module to connect by ssh to a child application and I perform commands like "ls", "history" and ...etc. 我使用Python pexpect模块通过ssh连接到子应用程序,并执行“ ls”,“ history”和... etc之类的命令。 I need help, to do operations like retrieve the sendline output and check if it contains a specific String chaine or other operations of that kind. 我需要帮助,以执行诸如检索sendline输出并检查其是否包含特定的String chaine或此类其他操作的操作。 Can somebody please help me? 有人能帮帮我吗?

This is a simple example of the code I use: 这是我使用的代码的一个简单示例:

child = pexpect.spawn('ssh -l karaf -p 8101 localhost')
child.logfile = open("/home/user/python_HR/logs.txt", "w")
child.expect('password:')
child.sendline(mypassword)
child.sendline(command1)

Here I need to perform an "if" which will check if the result of child.sendline(command1) contains the string chaine "test" 在这里,我需要执行一个“ if”,它将检查child.sendline(command1)的结果是否包含字符串链“ test”。

I already know how to save all outputs in a log file. 我已经知道如何将所有输出保存在日志文件中。 Also before and after attributes don't help me. 同样,之前和之后的属性也无济于事。 Thank you in advance. 先感谢您。

Since you are hitting the EOF then you can have code like this: 由于您正在击中EOF,因此您可以拥有如下代码:

index = pexpect.expect(['test', pexpect.EOF, pexpect.TIMEOUT])
    if index == 0:                                          
        do_something()
    elif index == 1:
        print(pexpect.before)
    elif index == 1:
        print(pexpect.before)

I expect that if you expect the EOF that you will be able to use .before attribute. 我希望如果您期望能够使用.before属性的EOF。

Alternatively: You can execute the command and pipe it's output to a file then download the file and work with it locally. 或者:您可以执行命令并将其输出通过管道传递到文件,然后下载文件并在本地使用它。

and if you want you can gain control manually by using pexpect.interact() 如果愿意,可以使用pexpect.interact()手动获得控制权

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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