关于 python docker sdk无法对容器文件进行重定向写入的问题(记录贴)

背景

需要通过docker的exec直接进入容器执行命令,需要将外部的一个变量写入容器内
,发现使用cat读文件的时候是没问题的,但是一旦使用echo ,cat 加上> >> <<<等就无法写入

解决

在 Docker 的exec_run中,某些复杂的 Shell 特性(如<<<<<)可能无法直接解析,因为这些特性依赖于 Shell 的高级功能,而exec_run默认可能不会启动一个完整的 Shell 环境。因此,当你尝试在exec_run中使用<<<<<时,可能会遇到问题。

为了解决这个问题,你可以通过以下方法确保命令在完整的 Shell 环境中执行:


方法 1:显式调用 Shell
exec_run中显式调用 Shell(如shbash),并使用-c参数来执行命令。这样可以确保 Shell 的高级特性(如<<<<<)被正确解析。

示例命令:

container.exec_run("sh -c 'cat <<< \"dfdfdf\" > /root/ctf/jk'")

或者使用bash

container.exec_run("bash -c 'cat <<< \"dfdfdf\" > /root/ctf/jk'")

方法 2:使用echo和管道
如果<<<无法解析,可以使用echo和管道(|)来实现相同的目的。这种方法更简单且兼容性更好。

示例命令:

container.exec_run("echo 'dfdfdf' | cat > /root/ctf/jk")

方法 3:使用printf和管道
printf是一个更强大的工具,可以格式化输出内容,并通过管道传递给cat

示例命令:

container.exec_run("printf 'dfdfdf' | cat > /root/ctf/jk")

方法 4:使用tee
如果你需要将内容写入文件并同时输出到标准输出,可以使用tee命令。tee命令通常不需要复杂的 Shell 特性,因此在exec_run中更容易使用。

示例命令:

container.exec_run("echo 'dfdfdf' | tee /root/ctf/jk")

完整示例代码
以下是一个完整的 Python 脚本,展示如何在 Docker 容器中使用这些方法:

import docker

client = docker.from_env()
container = client.containers.get("your_container_id")  # 替换为你的容器ID

# 确保路径存在
container.exec_run("mkdir -p /root/ctf")

# 方法 1:显式调用 Shell
result = container.exec_run("sh -c 'cat <<< \"dfdfdf\" > /root/ctf/jk'")
if result.exit_code == 0:
    print("写入成功(方法 1)")
else:
    print("写入失败(方法 1):", result.output.decode())

# 方法 2:使用 echo 和管道
result = container.exec_run("echo 'dfdfdf' | cat > /root/ctf/jk")
if result.exit_code == 0:
    print("写入成功(方法 2)")
else:
    print("写入失败(方法 2):", result.output.decode())

# 方法 3:使用 printf 和管道
result = container.exec_run("printf 'dfdfdf' | cat > /root/ctf/jk")
if result.exit_code == 0:
    print("写入成功(方法 3)")
else:
    print("写入失败(方法 3):", result.output.decode())

# 方法 4:使用 tee
result = container.exec_run("echo 'dfdfdf' | tee /root/ctf/jk")
if result.exit_code == 0:
    print("写入成功(方法 4)")
else:
    print("写入失败(方法 4):", result.output.decode())

总结
如果你在exec_run中遇到<<<<<无法解析的问题,可以尝试以下方法:

• 显式调用 Shell:使用sh -cbash -c来执行命令。

• 使用echo和管道:更简单且兼容性更好。

• 使用printf和管道:适用于需要格式化输出的场景。

• 使用tee:同时写入文件和输出到标准输出。

通过这些方法,你可以确保命令在 Docker 容器中正确执行,即使某些 Shell 特性无法直接解析。

posted @ 2025-02-26 16:36  学不会xuebuhui  阅读(32)  评论(0)    收藏  举报
Language: javascript //图片预览