python script to clean docker image

The function of this script is to check the disk usage of the specified path and perform corresponding operations based on the usage.

The specific script functions are as follows:

  1. Imported psutil and docker modules.
  2. A function called showDiskInfo is defined, which receives a path parameter and uses the psutil.disk_usage() function to obtain the disk usage of the path. Then, print out the disk usage, convert the bytes to GB units, and print out the total size, used, unused, and percentage used.
  3. A function named pruneImages is defined, which uses the docker.DockerClient object to connect to the Docker engine and calls the images.prune() method to clean up unused images.
  4. Call the showDiskInfo('/') function to get the disk usage of the root path and save the result in the DISKINFO variable.
  5. If the disk usage percentage is greater than 80%, print "greater than 80" and call the pruneImages() function to clean up unused Docker images; otherwise, print "less than 80".

Simply put, the purpose of this script is to check the disk usage of the root path, and if the usage exceeds 80%, clean up the unused images in the Docker engine.

#!/bin/python3

import psutil
import docker
 
#定义函数,参数为路径
 
def showDiskInfo(path):
 
    G = 1024*1024*1024
    
    diskinfo = psutil.disk_usage(path)
    
    print(path, diskinfo)
    
    #将字节转换成G
    
    print('%s 大小: %dG, 已使用: %dG, 未使用: %dG, 使用百分比:%d%%'%\
    
    (path, diskinfo.total//G, diskinfo.used//G, diskinfo.free//G,diskinfo.percent))

    return diskinfo.percent

def pruneImages():
    client = docker.DockerClient(base_url='unix://var/run/docker.sock',version='auto')
    # print(client.ping())
    try:
        client.images.prune(filters={
    
    'dangling': False})
        print("prune images successfully")
    except Exception as e:
        print(e)    

DISKINFO = showDiskInfo('/')
if DISKINFO > 80:
    print("大于80")
    pruneImages()
else:
    print("小于80")    



Guess you like

Origin blog.csdn.net/u010674101/article/details/133162156