gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 01:42:21 33 4
gpt4 key购买 nike

我想从 Python 脚本运行和控制 PSFTP,以便从 UNIX 机器上获取日志文件到我的 Windows 机器上。

我可以启动 PSFTP 并登录,但是当我尝试远程运行诸如“cd”之类的命令时,PSFTP 无法识别它,而只是在我关闭 PSFTP 时在终端中运行。

我尝试运行的代码如下:

import os

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

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

谢谢。

最佳答案

您需要将 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')

关于python - 我可以从 Python 脚本控制 PSFTP 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3659395/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com