views:

214

answers:

4

I'm attempting to use the python subprocess module to log in to a secure ftp site and then grab a file. However I keep getting hung up on just trying to send the password when it is requested. I so far have the following code:

from subprocess import Popen, PIPE

proc = Popen(['sftp','user@server', 'stop'], stdin=PIPE)
proc.communicate('password')

This still stops at the password prompt. If I enter the password manually it then goes to the ftp site and then enters the password on the command line. I've seen people suggest using pexpect but long story short I need a standard library solution. Is there anyway with subprocess and/or any other stdlib? What am I forgetting above?

A: 

Try

proc.stdin.write('yourPassword\n')
proc.stdin.flush()

That should work.

What you describe sounds like stdin=None where the child process inherits the stdin of the parent (your Python program).

Aaron Digulla
Hm... this still seems to be stopping and asking for the password.
The Jug
You do read stdout of the process in a second thread, don't you? Otherwise, odd things can happen. Also, check whether sftp allows a password from stdin by using `echo password | sftp ...` from the command line. It's possible that sftp always opens a shell.
Aaron Digulla
+2  A: 

Perhaps you should use an expect-like library instead?

For instance Pexpect (example). There are other, similar python libraries as well.

codeape
+1 for Pexpect. That is the right solution for interacting with console processes.
Chinmay Kanchi
Is there a stdlib expect module? I need to stick to stdlib.
The Jug
Pexpect is not stdlib. But it is pure python, so just put the pexpect.py file somewhere on your python path. For example next to your script file.
codeape
I'd rather not have to keep track of yet another non-standard library for our product since it's to something not super important anyway. However the library is still good from what I understand. From what I've seen there is no stdlib solution to this problem but I'll give you credit for the good library suggestion. I'm probably just gonna have our code call a bash script if anyone stumbles upon this question later and was wondering what I did.
The Jug
A: 

I would recommend scrapping the subprocess approach and using the paramiko package for sftp access.

mikerobi
A: 

I am stuck on a similar problem. I found Pexpect, but unfortunately it is not available for Windows. Did I miss any good expect-like library for Windows in my search?

iku
I'd probably ask this as it's own question rather then as an answer here. I'm not familiar with what is available on linux as opposed to Windows as far as libraries go.
The Jug