批量导出docker镜像

 

 脚本比较粗糙,可根据这个思想去改写自己的脚本

 

这里使用Python脚本来实现,熟悉subprocess.Popen, os.popen

docker save 镜像名(不需要加tag) -o tarname.tar

 

import re
import os
from subprocess import PIPE, Popen, STDOUT

if __name__ == "__main__":
    p = Popen('docker images', shell=True, stdout=PIPE, stderr=STDOUT)
    for line in p.stdout.readlines():
        # 此处的正则表达式是为了匹配镜像名以ufleet为开头的镜像 # 实际使用中根据需要自行调整
        m = re.match(r'(^ufleet[^\s]*\s*)\s([^\s]*\s)', line)
        # 镜像名
        iname = m.group(1).strip(' ')
        # tag
        itag = m.group(2)
        # tar包的名字
        tarname = iname.split('/')[-1]
        print(tarname)
        tarball = tarname + '.tar'
        ifull = iname + ':' + itag
        # save
        cmd = 'docker save -o ' + tarball + ' ' + ifull
        print(os.system(cmd))
# 将tar包放在临时目录 print(os.system('mv %s /tmp/xfleet/' % tarball)) retval = p.wait()

 

 

os.popen()用法

返回值是文件对象,既然是文件对象,使用完就应该关闭。推荐使用with来实现

import os

with os.popen(command, "r") as p: r = p.read()

read(): 读取整个文件,将文件内容放到一个字符串变量中

readline(): 每次读取一行;返回的是一个字符串对象,保持当前行的内存

readlines(): 一次性读取整个文件;自动将文件内容分析成一个行的列表

 

实现的一个小demon

docker images | awk '{print $1}' > images_cut.txt

import os

x=os.popen("cat ./images_cut.txt")
for item in x:
    tarname = item.split('/')[-1].strip()
    print(tarname)
    tarfile = "{}.tar".format(tarname)
    cmd = "docker save -o " + tarfile + " " + item
    print(os.system(cmd))

 

posted @ 2020-04-27 17:27  坚强的小蚂蚁  阅读(2517)  评论(0编辑  收藏  举报