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

StackOverflow https://stackoverflow.com/questions/19570206

  •  01-07-2022
  •  | 
  •  

Pregunta

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. 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. 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"

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.

¿Fue útil?

Solución

Since you are hitting the EOF then you can have code like this:

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.

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()

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top