我可以从Python脚本控制PSFTP吗?

时间:2010-09-07 14:09:00

标签: python unix scripting ftp sftp

我想从Python脚本运行和控制PSFTP,以便将UNIX文件夹中的日志文件存储到我的Windows机器上。

我可以启动PSFTP并登录但是当我尝试远程运行命令(例如'cd')时,PSFTP无法识别它,并且当我关闭PSFTP时它只是在终端中运行。

我尝试运行的代码如下:

import os

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

我只是想知道这是否真的可行。或者,如果有更好的方法在Python中执行此操作。

感谢。

2 个答案:

答案 0 :(得分:2)

您需要将PSFTP作为子流程运行,并直接与流程对话。 os.system每次调用时都会生成一个单独的子shell,因此无法像在命令提示符窗口中按顺序键入命令一样。查看标准Python subprocess模块的文档。你应该能够从那里完成你的目标。或者,可以使用一些Python SSH软件包,例如paramikoTwisted。如果你对PSFTP已经满意的话,我肯定会坚持尝试让它先工作。

子进程模块提示:

# 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')

答案 1 :(得分:1)

SFTP in Python? (platform independent)

中已经回答了这种问题

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

纯python方法的优点是你并不总是需要安装psftp。