3

I am using the python paramiko module to run a built in parmiko function SSH.execute on a remote server. I want to run a script on the server which will require 4 prompts. I was planning to do a more complex version of this:

   ExpectedString = 'ExpectedOutput'
   Output = SSH.execute('./runScript')
   if Output == ExpectedString:
       SSH.execute('Enter this')
   else:
       raise SomeException

The problem is nothing comes back for output as the server was waiting for a number to entered and the script gets stuck at this SSH.execute command. So even if another SSH.execute command is run after it never gets run! Should I be looking to use something other than paramiko?

2 Answers 2

3

You need to interact with the remote script. Actually, SSH.execute doesn't exist, I assume you're talking about exec_command. Instead of just returning the output, it actually gives you wrappers for stdout, stdin and stderr streams. You can directly use these in order to communicate with the remote script.

Basically, this is how you run a command and pass data over stdin (and receive output using stdout):

ssh.connect('127.0.0.1', username='foo', password='bar')

stdin, stdout, stderr = ssh.exec_command("some_script")

stdin.write('expected_input\n')
stdin.flush()

data = stdout.read.splitlines()

You should check for the prompts, of course, instead of relying on good timing.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your answer! Would you mind explaining the process behind what the meaning of using stdin.write,stdin.flush and data is for ?
in short: your application receives data using stdin and outputs data using stdout (and stderr for errors, usually, you don't notice that there's a difference as a shell displays both). In Python, you can use them pretty much like file objects (which are actually streams as well), i.e. read, write, flush... docs.python.org/library/io.html
this solution doesn't work for me- execution of ssh.exec_command still hangs as before waiting for an input so no output is returned to the python script.
0

@leoluk - yep, I understand your problem, both those recommended solutions won't work. The problem, as you said, with exec_command is that you can only read the output once the command completes. So, if you wanted to remotely run the command rm -i *, you won't be able to read which file is to be deleted before you can respond with a "yes" or a "no". The key here is to use invoke_shell. See this youtube link - https://www.youtube.com/watch?v=lLKdxIu3-A4 - this helped and got me going.

Comments

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.