views:

45

answers:

2

Hi,

i want to run and control PSFTP from a Python script in order to get log files from a UNIX box onto my Windows machine.

I can start up PSFTP and log in but when i try to run a command remotely such as 'cd' it isn't recognised by PSFTP and is just run in the terminal when i close PSFTP.

The code which i am trying to run is as follows:

import os

os.system("<directory> -l <username> -pw <password>" )
os.system("cd <anotherDirectory>")

i was just wondering if this is actually possible. Or if there is a better way to do this in Python.

Thanks.

A: 

You'll need to run PSFTP as a subprocess and speak directly with the process. os.system spawns a separate subshell each time it's invoked so it doesn't work like typing commands sequentially into a command prompt window. Take a look at the documentation for the standard Python subprocess module. You should be able to accomplish your goal from there. Alternatively, there are a few Python SSH packages available such as paramiko and Twisted. If you're already happy with PSFTP, I'd definitely stick with trying to make it work first though.

Subprocess module hint:

# The following line spawns the psftp process and binds its standard input
# to p.stdin and its standard output to p.stdout
p = subprocess.Popen('psftp -l testuser -pw testpass'.split(), 
                     stdin=subprocess.PIPE, stdout=subprocess.PIPE)
# Send the 'cd some_directory' command to the process as if a user were 
# typing it at the command line
p.stdin.write('cd some_directory\n')
Rakis
I've taken a look at subprocess and i can get PSFTP to run but i still can't figure out how to send commands to it?? Any ideas??
matt2010
Edited to provide subprocess module example
Rakis
A: 

This has sort of been answered in: http://stackoverflow.com/questions/432385/sftp-in-python-platform-independent

http://www.lag.net/paramiko/

The advantage to the pure python approach is that you don't always need psftp installed.

Gregor
I've seen this, but i don't want to use a third party library to do this. But thanks for the answer!!
matt2010