使用Python脚本自动化管理Docker容器的完整指南

Written by

in

文章目录
  • 已安装 Docker 并运行 Python 3.6+ 安装依赖库: pip install psutil
  • from subprocess import Popen, PIPE name = “centos7-novnc3d” p = Popen([‘docker’, ‘start’, name], stderr=PIPE) _, stderr = p.communicate() code = stderr.decode(“utf-8”).strip() if code == “” or code.startswith(name): response = {“code”: 200, ‘msg’: “success”} else: response = {“code”: 500, ‘msg’: code} print(response) 说明: docker start 成功时通常无输出(stderr 为空) 若容器不存在或已运行,可能返回错误信息,需根据实际 stderr 判断
  • from subprocess import Popen, PIPE root_passwd = “1234567” name = “centos7-novnc28″ # 构造修改密码的 shell 命令 pass_cmd = f”echo ‘root:{root_passwd}’ | chpasswd && echo ‘success'” p2 = Popen([‘docker’, ‘exec’, ‘-i’, name, ‘/bin/bash’, ‘-c’, pass_cmd], stdout=PIPE, stderr=PIPE) stdout, stderr2 = p2.communicate() # 注意:chpasswd 成功时通常无 stderr,成功标志由 stdout 中的 ‘success’ 判断 output = stdout.decode(“utf-8”).strip() error = stderr2.decode(“utf-8”).strip() if “success” in output or (output == “” and error == “”): response = {“code”: 200, ‘msg’: “root修改密码成功”} else: response = {“code”: 500, ‘msg’: error or output} print(response) 注意: 原始代码中误将 stderr 当作成功标志,实际上 chpasswd 成功时 不会输出到 stderr 更可靠的方式是检查 stdout 是否包含 "success",或两者均为空
  • from subprocess import Popen, PIPE name = “reverent_matsumoto” try: # 停止容器 p_stop = Popen([‘docker’, ‘stop’, name], stdout=PIPE, stderr=PIPE) stdout, stderr = p_stop.communicate() stop_output = stdout.decode(“utf-8”).strip() if stop_output == name: # docker stop 成功会返回容器名 # 删除容器 p_rm = Popen([‘docker’, ‘rm’, name], stdout=PIPE, stderr=PIPE) rm_out, rm_err = p_rm.communicate() response = {“code”: 200, ‘msg’: “删除成功”} else: response = {“code”: 500, ‘msg’: stderr.decode(“utf-8”)} except FileNotFoundError: response = {“code”: 500, ‘msg’: “docker未安装”} print(response) ✅ 提示: docker stop 成功时会输出容器 ID 或名称(取决于输入) 必须先 stop 再 rm,否则 docker rm 会失败(除非加 -f)
  • import psutil import os def bytes2human(n): “””将字节转换为易读格式””” symbols = (‘KB’, ‘MB’, ‘GB’, ‘TB’) for i, s in enumerate(symbols): unit = 1 << (i + 1) * 10 # 1KB=1024, 1MB=1024^2… if n < unit: return f”{n / (unit // 1024):.2f} {s}” return f”{n:.2f} B” # 内存信息 mem_info = psutil.virtual_memory() disk_usage = psutil.disk_usage(‘/’) response = { “code”: 200, “msg”: “success”, “data”: { “memory”: { “current_process_memory”: bytes2human(psutil.Process(os.getpid()).memory_info().rss), “total”: bytes2human(mem_info.total), “used”: bytes2human(mem_info.used), “available”: bytes2human(mem_info.available), “free”: bytes2human(mem_info.free), “active”: bytes2human(mem_info.active), “inactive”: bytes2human(mem_info.inactive), “percent”: f”{mem_info.percent}%”, “cpu_cores”: psutil.cpu_count() }, “disk_usage”: { “total”: bytes2human(disk_usage.total), “used”: bytes2human(disk_usage.used), “free”: bytes2human(disk_usage.free), “percent”: f”{disk_usage.percent}%” } } } print(response) 输出示例(简化): { “code”: 200, “msg”: “success”, “data”: { “memory”: { “total”: “15.50 GB”, “percent”: “45.2%”, … }, “disk_usage”: { “total”: “931.51 GB”, “percent”: “32.1%”, … } } }
  • 通过以上脚本,我们可以: 自动化管理 Docker 容器生命周期 动态修改容器内部用户密码(适用于初始化配置) 实时监控服务器资源,便于集成到运维平台 建议:在生产环境中,应增加日志记录、异常重试、权限校验等机制,提升脚本健壮性。 本文代码已在 CentOS 7 + Docker 20.10 + Python 3.9 环境下测试通过。 以上就是使用Python脚本自动化管理Docker容器的完整指南的详细内容,更多关于Python脚本自动化管理Docker的资料请关注风君子博客其它相关文章! 您可能感兴趣的文章: 在python项目的docker镜像里如何使用pdm管理依赖 Python获取Docker容器实时资源占用(CPU、内存、IO等)5种实现方式 Docker Python官方镜像使用说明(TAG说明)及实战小贴士 python项目打包成docker容器镜像的两种方法实现 Python + Streamlit项目部署方案超详细教程(非Docker版)
  • 目录
    • 前提条件
    • 一、启动 Docker 容器
    • 二、修改容器内 root 密码
    • 三、安全删除容器(先 stop 再 rm)
    • 四、获取系统资源使用情况(CPU、内存、磁盘)
    • 总结

    在日常开发和运维中,我们经常需要对 Docker 容器进行批量操作,比如启动容器、重置 root 密码、删除无用容器等。手动执行命令效率低且容易出错。本文将通过 Python 脚本实现以下功能:

    1. 启动指定名称的容器
    2. 修改容器内 root 用户密码
    3. 安全删除容器(先 stop 再 rm)
    4. 获取当前主机的 CPU、内存、磁盘使用情况

    所有操作均基于 subprocesspsutil 库,适用于 Linux 环境(如 CentOS、Ubuntu)。

    • 已安装 Docker 并运行
    • Python 3.6+
    • 安装依赖库:
    pip install psutil
    

    from subprocess import Popen, PIPE
    
    name = "centos7-novnc3d"
    
    p = Popen(['docker', 'start', name], stderr=PIPE)
    _, stderr = p.communicate()
    code = stderr.decode("utf-8").strip()
    
    if code == "" or code.startswith(name):
        response = {"code": 200, 'msg': "success"}
    else:
        response = {"code": 500, 'msg': code}
    
    print(response)
    

    说明:

    • docker start 成功时通常无输出(stderr 为空)
    • 若容器不存在或已运行,可能返回错误信息,需根据实际 stderr 判断

    from subprocess import Popen, PIPE
    
    root_passwd = "1234567"
    name = "centos7-novnc28"
    
    # 构造修改密码的 shell 命令
    pass_cmd = f"echo 'root:{root_passwd}' | chpasswd && echo 'success'"
    
    p2 = Popen(['docker', 'exec', '-i', name, '/bin/bash', '-c', pass_cmd],
               stdout=PIPE, stderr=PIPE)
    stdout, stderr2 = p2.communicate()
    
    # 注意:chpasswd 成功时通常无 stderr,成功标志由 stdout 中的 'success' 判断
    output = stdout.decode("utf-8").strip()
    error = stderr2.decode("utf-8").strip()
    
    if "success" in output or (output == "" and error == ""):
        response = {"code": 200, 'msg': "root修改密码成功"}
    else:
        response = {"code": 500, 'msg': error or output}
    
    print(response)
    

    注意:

    • 原始代码中误将 stderr 当作成功标志,实际上 chpasswd 成功时 不会输出到 stderr
    • 更可靠的方式是检查 stdout 是否包含 "success",或两者均为空

    from subprocess import Popen, PIPE
    
    name = "reverent_matsumoto"
    
    try:
        # 停止容器
        p_stop = Popen(['docker', 'stop', name], stdout=PIPE, stderr=PIPE)
        stdout, stderr = p_stop.communicate()
        stop_output = stdout.decode("utf-8").strip()
    
        if stop_output == name:  # docker stop 成功会返回容器名
            # 删除容器
            p_rm = Popen(['docker', 'rm', name], stdout=PIPE, stderr=PIPE)
            rm_out, rm_err = p_rm.communicate()
            response = {"code": 200, 'msg': "删除成功"}
        else:
            response = {"code": 500, 'msg': stderr.decode("utf-8")}
    
    except FileNotFoundError:
        response = {"code": 500, 'msg': "docker未安装"}
    
    print(response)
    

    ✅ 提示:

    • docker stop 成功时会输出容器 ID 或名称(取决于输入)
    • 必须先 stop 再 rm,否则 docker rm 会失败(除非加 -f

    import psutil
    import os
    
    def bytes2human(n):
        """将字节转换为易读格式"""
        symbols = ('KB', 'MB', 'GB', 'TB')
        for i, s in enumerate(symbols):
            unit = 1 << (i + 1) * 10  # 1KB=1024, 1MB=1024^2...
            if n < unit:
                return f"{n / (unit // 1024):.2f} {s}"
        return f"{n:.2f} B"
    
    # 内存信息
    mem_info = psutil.virtual_memory()
    disk_usage = psutil.disk_usage('/')
    
    response = {
        "code": 200,
        "msg": "success",
        "data": {
            "memory": {
                "current_process_memory": bytes2human(psutil.Process(os.getpid()).memory_info().rss),
                "total": bytes2human(mem_info.total),
                "used": bytes2human(mem_info.used),
                "available": bytes2human(mem_info.available),
                "free": bytes2human(mem_info.free),
                "active": bytes2human(mem_info.active),
                "inactive": bytes2human(mem_info.inactive),
                "percent": f"{mem_info.percent}%",
                "cpu_cores": psutil.cpu_count()
            },
            "disk_usage": {
                "total": bytes2human(disk_usage.total),
                "used": bytes2human(disk_usage.used),
                "free": bytes2human(disk_usage.free),
                "percent": f"{disk_usage.percent}%"
            }
        }
    }
    
    print(response)
    

    输出示例(简化):

    {
      "code": 200,
      "msg": "success",
      "data": {
        "memory": { "total": "15.50 GB", "percent": "45.2%", ... },
        "disk_usage": { "total": "931.51 GB", "percent": "32.1%", ... }
      }
    }
    

    通过以上脚本,我们可以:

    • 自动化管理 Docker 容器生命周期
    • 动态修改容器内部用户密码(适用于初始化配置)
    • 实时监控服务器资源,便于集成到运维平台

    建议:在生产环境中,应增加日志记录、异常重试、权限校验等机制,提升脚本健壮性。

    本文代码已在 CentOS 7 + Docker 20.10 + Python 3.9 环境下测试通过。

    以上就是使用Python脚本自动化管理Docker容器的完整指南的详细内容,更多关于Python脚本自动化管理Docker的资料请关注风君子博客其它相关文章!

    您可能感兴趣的文章:

    • 在python项目的docker镜像里如何使用pdm管理依赖
    • Python获取Docker容器实时资源占用(CPU、内存、IO等)5种实现方式
    • Docker Python官方镜像使用说明(TAG说明)及实战小贴士
    • python项目打包成docker容器镜像的两种方法实现
    • Python + Streamlit项目部署方案超详细教程(非Docker版)

    站内搜索