# -*- coding: UTF-8 -*- import docker #初始化客户端 client = docker.from_env() #from_env Return a client configured from environment variables. #连接环境变量中的docker 如 DOCKER_HOST DOCKER_TLS_VERIFY DOCKER_CERT_PATH # client = docker.DockerClient(base_url=‘unix://var/run/docker.sock‘) # client = docker.DockerClient(base_url=‘tcp://172.29.206.148:2375‘) # for container in client.containers.list(): # print(container.id) # print(container.short_id) # print(container.name) # print(container.status) # print(container.image) # print(container.attrs) #all=True 默认只列出running的容器 container_list=[] for container in client.containers.list(all=True): container_info={} container_info["name"]=container.name container_info["id"]=container.id container_info["short_id"]=container.short_id container_info["status"]=container.status container_info["image"]=container.image.tags container_list.append(container_info) # for i in container_list: # for k,v in i.items(): # print "key %s , val %s" %(k,v) #获取容器进行操作 #container=client.containers.get("***") 可以是容器的id或name或short_id #force=True running的容器正常删除须先stop在 remove # 强制删除须加 force=True for i in container_list: container=client.containers.get(i["id"]) print("operate %s",%(i["name"])) container.stop() container.rename()#重命名 container.kill()#强制停止 container.start()#启动 Container.restart()#重启 container.remove(force=True)#running的容器强制删除须加 force=True # 列出镜像 for i in client.images.list(): print i.id print i.short_id print i.tags # 删除镜像 client.images.remove("c9d43a597ff0")