Search code examples
bashsshspawnpexpect

Python module pexpect - how to connect to ssh server and then run bash commands


I'm new and I couldn't find a full answer to my question. So I'm asking it here. I'm using python and the pexpect module to connect to an ssh server and run a few commands. However some of the commands don't work. I looked at the documentation and I can see that running a command like:

ls -l | grep -i <Filter>

Because I have to use the spawn command to run the bash script with a

child = pexpect.spawn('/bin/bash -c "ls -l | grep LOG > logs.txt"')

However, the way I connect to the server is by sending an ssh command with a key:

p = pexpect.spawn("ssh -t -t NAME@IP -i ~/.ssh/Keyfile ")

So I can't run the spawn command with the bash command inside it (or can I?)

The response should be a password request because its re-directing me to another machine.

How do I use the spawn command so I can connect to the server with the key enter the password for the re-directed machine and then run a bash command.

Note: I'm trying to figure out the bash part. The Connection to the server and the re-direction + password insertion already work for me.


Solution

  • You may send the command in the next line:

    ssh = pexpect.spawn('ssh  -t -t NAME@IP -i ~/.ssh/Keyfile')
    #You may write expect here to check if the ask if for password or some other error or the initial banner message
    ssh.sendline('password')
    #You may check if the password is successful
    ssh.sendline('/bin/bash -c "ls -l | grep LOG > logs.txt"');