Python 脚本,使用共享文件或目录进入 Docker 镜像内部的 CLI,并将用户输入作为容器的命令执行

问题描述 投票:0回答:0

我下面的代码使用已知的现有文件名(此文件存储在压缩文件夹中,因此我必须解压缩它才能获取文件)。我创建一个新目录,然后将工作目录更改为新目录。我解压缩目标文件的已知现有位置。然后我得到该文件的文件大小,所以我知道我确实正确地解压缩了它。在此之后,我使用 shlex.split()shlex.quote() 的组合来帮助解析命令。 docker 命令以交互方式运行,analyze_dir 目录将从本地主机共享并复制到 docker 容器的/home/remnux/files 目录中。因此,文件 filename.txt 应该已被复制并放置在容器中。我相信它正在被复制,但我无法处理带有空格或任何复杂程度的命令。我是否错误地实现了这个功能,让用户通过 docker 容器中的终端输入命令?

ls files
返回: 文件

这应该返回文件名.txt。

echo "hello world"
根本不返回任何输出。
echo hello
也没有。

pwd
hostname
这样的非常基本的命令正在工作。

Hostname
表明我实际上在 docker 容器内,因为它返回一个字母数字字符串。

这是我目前使用的脚本:

import os
import random
import zipfile
import subprocess
import shlex

# known file name (unzipped)
file_name = "filename.txt"
analyze_dir = f'/home/files/analyze-{random.randint(1, 1000000)}'
os.makedirs(analyze_dir, exist_ok=True)
os.chdir(analyze_dir)

# known file location (but it's zipped location)
with zipfile.ZipFile('/home/files/filename.zip', 'r') as zip_ref:
    zip_ref.extractall(pwd=b'infected')
unzipped_file_path = os.path.join(analyze_dir, file_name)
file_size = os.path.getsize(unzipped_file_path)

# print file size so I know I have the file
print(file_size)

# print directory so I know the file was pushed into the directory
print(analyze_dir)

command = input("Enter command to run inside Docker container: ")
command_args = shlex.split(command)
docker_command = f"docker run --rm -it --network none -u remnux -v {analyze_dir}:/home/remnux/files remnux/remnux-distro bash -c {shlex.quote(command)}"
print(docker_command)

process = subprocess.Popen(shlex.split(docker_command), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = process.communicate()
result = output.decode() if output else error.decode()
print(f"Output: {result}")
python docker shell
© www.soinside.com 2019 - 2024. All rights reserved.