我可以通过 Python 脚本控制 PSFTP 吗?
我想从 Python 脚本运行和控制 PSFTP,以便将日志文件从 UNIX 机器获取到我的 Windows 机器上。
我可以启动 PSFTP 并登录,但是当我尝试远程运行命令(例如“cd”)时,PSFTP 无法识别它,并且当我关闭 PSFTP 时它只是在终端中运行。
我试图运行的代码如下:
import os
os.system("<directory> -l <username> -pw <password>" )
os.system("cd <anotherDirectory>")
我只是想知道这是否真的可能。或者是否有更好的方法在 Python 中执行此操作。
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要将 PSFTP 作为子进程运行并直接与该进程对话。 os.system 每次调用时都会生成一个单独的子 shell,因此它不像在命令提示符窗口中按顺序键入命令那样工作。查看标准 Python
subprocess
模块的文档。从那里你应该能够实现你的目标。另外,还有一些可用的 Python SSH 软件包,例如 paramiko 和 扭曲。如果您已经对 PSFTP 感到满意,我肯定会坚持首先尝试让它工作。子流程模块提示:
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 Pythonsubprocess
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:
这已经在以下内容中得到了回答:SFTP in Python? (与平台无关)
http://www.lag.net/paramiko/
纯 python 方法的优点是您并不总是需要安装 psftp。
This has sort of been answered in: 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.