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

标签 python unix scripting ftp sftp

我想从 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/

相关文章:

linux - 将最后四行移动到文本文件中的第二行

java - 从 Java 执行带反引号的 Unix 命令

linux - 在脚本中启动 shell

Python Streamlit - 在不重新运行整个脚本的情况下过滤 Pandas 数据框

linux - 快速 unix 命令在文件中间显示特定行?

lua - 您如何干净地退出交互式Lua?

javascript - 针对特定文本框架的 InDesign 脚本

Python图像旋转角度计算

python - 识别 Python 字符串中的\literally

python - Raven Twisted 集成的 SSL 选项