imágenes.txt contenido
harbor.xxx.com/kjgh/aaa:1.0.0
harbor.xxx.com/kjgh/bbb:1.0.0
Python2 extrae y exporta el código del programa de imagen acoplable (sin compresión)
El siguiente es un programa escrito en la sintaxis de Python 2, y el problema de codificación está resuelto:
si solo necesita nombrar el archivo tar de acuerdo con el nombre de la imagen, reescríbalo de la siguiente manera:
output_file = os.path.join(output_dir, "{}.tar".format(image_name.rsplit("/", 1)[-1]))
# -*- coding: utf-8 -*-
import subprocess
import os
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
def pull_docker_image(image_name):
try:
# 检查镜像是否已存在
check_output = subprocess.check_output(['docker', 'images', '-q', image_name])
if check_output.strip():
print("The image '{}' already exists.".format(image_name))
else:
# 拉取镜像
subprocess.call(['docker', 'pull', image_name])
print("The image '{}' has been pulled successfully.".format(image_name))
except subprocess.CalledProcessError as e:
print("An error occurred while pulling the image '{}': {}".format(image_name, e))
# 定义导出镜像的函数
def export_docker_images(output_dir):
# 检查输出目录是否存在,如果不存在则创建
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# 读取 images.txt 中定义的镜像列表
with open('images.txt', 'r') as file:
for line in file:
image_name = line.strip()
# 拉取镜像
pull_docker_image(image_name)
# 导出镜像为 tar 文件
output_file = os.path.join(output_dir, "{}.tar".format(image_name.replace('/', '-')))
subprocess.call(['docker', 'save', '-o', output_file, image_name])
print("The image '{}' has been exported to '{}'.".format(image_name, output_file))
# 主程序
if __name__ == "__main__":
# 指定导出目录
output_directory = "exported_images"
# 导出镜像
export_docker_images(output_directory)
En esta versión, agregamos # -*- coding: utf-8 -*-
para especificar la codificación del archivo como UTF-8. Además, usamos reload(sys)
y sys.setdefaultencoding('utf-8')
para establecer la codificación predeterminada en UTF-8 para resolver el problema del manejo de caracteres Unicode en Python 2.
Asegúrese de que Docker se haya instalado antes de ejecutar el programa y que el programa Python tenga permiso para ejecutar los comandos de Docker. Además, asegúrese de que images.txt
el archivo exista y contenga la lista correcta de nombres de réplicas. La imagen exportada se guardará en el directorio de salida especificado.
Comprime cada tar en un archivo gz separado
# -*- coding: utf-8 -*-
import subprocess
import os
import sys
import tarfile
import gzip
reload(sys)
sys.setdefaultencoding('utf-8')
def pull_docker_image(image_name):
try:
# 检查镜像是否已存在
check_output = subprocess.check_output(['docker', 'images', '-q', image_name])
if check_output.strip():
print("The image '{}' already exists.".format(image_name))
else:
# 拉取镜像
subprocess.call(['docker', 'pull', image_name])
print("The image '{}' has been pulled successfully.".format(image_name))
except subprocess.CalledProcessError as e:
print("An error occurred while pulling the image '{}': {}".format(image_name, e))
# 定义导出镜像的函数
def export_docker_images(output_dir):
# 检查输出目录是否存在,如果不存在则创建
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# 读取 images.txt 中定义的镜像列表
with open('images.txt', 'r') as file:
for line in file:
image_name = line.strip()
# 拉取镜像
pull_docker_image(image_name)
# 导出镜像为 tar 文件
output_file = os.path.join(output_dir, "{}.tar".format(image_name.replace('/', '-')))
subprocess.call(['docker', 'save', '-o', output_file, image_name])
print("The image '{}' has been exported to '{}'.".format(image_name, output_file))
# 压缩 tar 文件为 gzip
gzip_file = "{}.gz".format(output_file)
with open(output_file, 'rb') as f_in, gzip.open(gzip_file, 'wb') as f_out:
f_out.writelines(f_in)
# 删除原始的 tar 文件
os.remove(output_file)
print("The image '{}' has been compressed to '{}'.".format(image_name, gzip_file))
# 主程序
if __name__ == "__main__":
# 指定导出目录
output_directory = "exported_images"
# 导出镜像
export_docker_images(output_directory)
Combinar y comprimir múltiples tars espejo en un archivo gz
# -*- coding: utf-8 -*-
import subprocess
import os
import sys
import tarfile
import gzip
reload(sys)
sys.setdefaultencoding('utf-8')
def pull_docker_image(image_name):
try:
# 检查镜像是否已存在
check_output = subprocess.check_output(['docker', 'images', '-q', image_name])
if check_output.strip():
print("The image '{}' already exists.".format(image_name))
else:
# 拉取镜像
subprocess.call(['docker', 'pull', image_name])
print("The image '{}' has been pulled successfully.".format(image_name))
except subprocess.CalledProcessError as e:
print("An error occurred while pulling the image '{}': {}".format(image_name, e))
# 定义导出镜像的函数
def export_docker_images(output_file):
# 创建 tar 文件
with tarfile.open(output_file, "w:gz") as tar:
# 读取 images.txt 中定义的镜像列表
with open('images.txt', 'r') as file:
for line in file:
image_name = line.strip()
# 拉取镜像
pull_docker_image(image_name)
# 导出镜像为 tar 文件
temp_file = "{}.tar".format(image_name.replace('/', '-'))
subprocess.call(['docker', 'save', '-o', temp_file, image_name])
print("The image '{}' has been exported to '{}'.".format(image_name, temp_file))
# 添加到 tar 文件
tar.add(temp_file, arcname=os.path.basename(temp_file))
# 删除临时的 tar 文件
os.remove(temp_file)
print("The image '{}' has been added to the tar archive.".format(image_name))
print("All images have been exported and compressed to '{}'.".format(output_file))
# 主程序
if __name__ == "__main__":
# 指定导出的 tar.gz 文件
output_file = "exported_images.tar.gz"
# 导出并压缩镜像
export_docker_images(output_file)