Question

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.

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top