我可以从Python脚本控制PSFTP吗?
我想通过一个Python脚本来运行和控制PSFTP,以便把UNIX系统上的日志文件传到我的Windows电脑上。
我可以启动PSFTP并登录,但当我尝试在远程运行像'cd'这样的命令时,PSFTP并不识别这个命令,而是直接在终端中执行,等我关闭PSFTP后才会看到结果。
我尝试运行的代码如下:
import os
os.system("<directory> -l <username> -pw <password>" )
os.system("cd <anotherDirectory>")
我只是想知道这是否真的可行,或者在Python中有没有更好的方法来做到这一点。
谢谢。
2 个回答
1
2
你需要把PSFTP当作一个子进程来运行,并直接和这个进程交流。使用os.system
每次都会启动一个新的子命令行,这样就不能像在命令提示符窗口里连续输入命令那样工作。你可以看看Python标准库里的subprocess
模块的文档,应该能从中找到实现你目标的方法。另外,还有一些Python的SSH库,比如paramiko和Twisted。如果你已经习惯使用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')