docker模块-清理非Running状态的历史容器

清理非Running状态的历史容器

#!/usr/bin/python3
import docker
import time
import datetime
import sys
# docker version -> API version:1.40
client = docker.APIClient(base_url='unix://var/run/docker.sock',
                          version='1.39',
                          timeout=15)

# print(client.version())
# 清除未使用的images

# 删除一天前非running状态的container
def rmcontaioner():
    for x in client.containers(before=True, all=True):
        print('所有的Container信息:', x, end='\n')
        if x['State'] != 'running':
            # a = x['Created']
            # print(x['Names'], x['State'], x['Created'])
            # print(, a, time.asctime(time.localtime(a)))

            now = datetime.datetime.now()
            start = datetime.datetime.fromtimestamp(x['Created'])
            stop = now - start
            # print('此Container {} 已经非运行状态时间为 :{} Day'.format(x['Names'], stop.days))
            if str(stop.days) >= str(1):
                print('将要被删除的Container :', x['Names'])
                client.remove_container(x)

if __name__ == "__main__":
    try:
        if sys.argv[1] == 'container':
            rmcontaioner()
        elif sys.argv[1] == 'images':
            # rmimages()
            pass
        else:
            print("....")
    except Exception as e:
        print('....')
posted @ 2021-05-30 15:06  SRE运维充电站  阅读(118)  评论(0编辑  收藏  举报