views:

3273

answers:

4

Hi, I'm trying to run an interactive command through paramiko. The cmd execution tries to prompt for a password but I do not know how to supply the password through paramiko's exec_command and the execution hangs. Is there a way to send values to the terminal if a cmd execution expects input interactively?

ssh = paramiko.SSHClient()
ssh.connect(server, username=username, password=password)
ssh_stdin, ssh_stdout, ssh_stderr = ssh_session.exec_command("psql -U factory -d factory -f /tmp/data.sql")

Does anyone know how this can addressed? Thank you.

+1  A: 

I'm not familiar with paramiko, but this may work:

ssh_stdin.write('input value')
ssh_stdin.flush()

For information on stdin:

http://docs.python.org/library/sys.html?highlight=stdin#sys.stdin

monkut
+4  A: 

The full paramiko distribution ships with a lot of good examples: http://www.lag.net/paramiko/

In the demos subdirectory, demo.py and interactive.py have full interactive TTY examples which would probably be overkill for your situation.

In your example above ssh_stdin acts like a standard Python file object, so ssh_stdin.write should work so long as the channel is still open.

I've never needed to write to stdin, but the docs suggest that a channel is closed as soon as a command exits, so using the standard stdin.write method to send a password up probably won't work. There are lower level paramiko commands on the channel itself that give you more control - see how the SSHClient.exec_command method is implemented for all the gory details.

Alabaster Codify
A: 

The only way to do this in paramikio, will be to invoke a shell, like in demo.py, demo_simple.py, and interactive.py. Using exec_command is essentially like the using the ssh syntax of

ssh user@host command

Once you have in interactive session, you will also need to do some "expect" like handling, in order to wait for the password prompt, and send the password at the correct time.

You could also change the method of authentication, so that a password isn't required.

Another option is to use a database library to connect to the database directly without the need of the shell/psql session. If you're looking for security, you could tunnel this connection over an ssh channel, or simply use tls.

JimB
A: 

You need Pexpect to get the best of both worlds (expect and ssh wrappers).

ax25