我能否从Python脚本中控制PSFTP?

3
我希望能够从Python脚本中运行和控制PSFTP,以便将UNIX盒子上的日志文件传输到我的Windows机器。我可以启动PSFTP并登录,但是当我尝试远程运行命令(例如'cd')时,PSFTP无法识别它,而只是在我关闭PSFTP后在终端中运行。我正在尝试运行以下代码:
import os

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

我在想这是否真的可能。或者用Python做这件事有更好的方法吗?
谢谢。
2个回答

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

我已经查看了子进程,可以运行PSFTP,但我仍然无法弄清如何向其发送命令?有什么想法吗? - matt2010
编辑以提供subprocess模块示例 - Rakis

1

我看到过这个,但我不想使用第三方库来完成这个。不过还是谢谢你的回答!! - matt2010

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接