1

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.

1 Answer 1

2

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"');
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks i dont know why this obvious solution did not come to me :) Also note that i tried this on an android device too where there is no /bin/bash but rather bin/sh i had to state bin was located system so the result would be ssh.sendline('system/bin/sh -c "ls -l | grep LOG > logs.txt"'); if anyone is intrested

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.