我想从Python脚本运行并控制PSFTP,以便将来自UNIX框的日志文件放到我的Windows机器上。
我可以启动PSFTP并login,但是当我尝试远程运行一个命令如“cd”时,它不能被PSFTP识别,只是在closuresPSFTP时在terminal中运行。
我试图运行的代码如下所示:
import os os.system("<directory> -l <username> -pw <password>" ) os.system("cd <anotherDirectory>")
我只是想知道这是否可能。 或者,如果有更好的方法在Python中做到这一点。
谢谢。
您需要将PSFTP作为子流程运行,并直接与流程对话。 os.system
在每次调用时os.system
产生一个单独的子shell,所以它不能像按顺序将命令输入到命令提示符窗口那样工作。 看看标准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')