Search code examples
pythonsshpexpect

How do I use pexpect to run things in the background?


I am using the 'Pexpect' library in a script and wanted to do some operations after that. What I am doing is as follows:

def child():
        pexpect.spawn("ssh [email protected]")
        child.expect(".*password.*")
        child.sendline('tranzmeo1@#')
        print(child.before)
        child.interact()
        return

This is a function I call from another file (which I call training.) When I run training, the child() is called, but immediately it stops the program and enters into the tranzmeo console, which I don't want. I need to ssh into it and do some operations in the background in tranzmeo. How can I do that using pexpect?

My operation is as follows(just for your reference):

def scp(tensorflow_file_location_temp ,tensorflow_file_loc)
        child = pexpect.spawn("scp -r " + tensorflow_file_location_temp + "[email protected]:" + tensorflow_file_location )
        child.expect(".*password.*")
        child.sendline('Tranzmeo1@#')
        child.interact()

Solution

  • .interact() gives control of the child process to the interactive user (the human at the keyboard). Keystrokes are sent to the child process, and the stdout and stderr output of the child process is printed.

    If you don't want that, don't call it! You want to continue working with the object returned from pexpect.spawn("ssh [email protected]") (the code you posted doesn't assign that to child, which I assume is a copy-paste error):

    child.sendline("scp -r " + tensorflow_file_location_temp + "[email protected]:" + tensorflow_file_location)
    

    But you ought to set up ssh keys, then you'll be able to do what you want without passwords and pexpect altogether by simply running scp.