批量導出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))

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM