You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows环境下,如何用Python脚本自动启动远程Docker容器?

实现远程Docker容器开机自动启动的Python方案

核心逻辑

通过Python的paramiko库建立SSH连接到远程服务器,执行Docker命令批量启动容器,再将脚本配置为Windows开机自启项,实现开机后自动触发远程容器启动操作。

1. 安装依赖

首先安装用于SSH远程连接的paramiko库:

pip install paramiko

2. 编写Python脚本

脚本实现SSH连接、远程执行Docker启动命令的完整逻辑,同时包含异常处理:

import paramiko
import time
import os

def start_remote_docker_containers():
    # 远程服务器配置信息
    hostname = "dummy_name.com"
    username = "替换为你的远程SSH用户名"
    # 推荐通过环境变量存储密码,避免明文泄露
    password = os.getenv("REMOTE_SSH_PWD")

    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(hostname, username=username, password=password, timeout=15)

        # 执行命令:启动所有已停止的容器(运行中容器重复启动无影响)
        # 若要强制启动所有容器,可替换为 `docker start $(docker ps -aq)`
        stdin, stdout, stderr = ssh.exec_command("docker start $(docker ps -aq -f status=exited)")
        
        output = stdout.read().decode().strip()
        error = stderr.read().decode().strip()

        if error:
            print(f"执行错误: {error}")
        else:
            print(f"容器启动结果: {output if output else '当前无需要启动的容器'}")

        ssh.close()
    except Exception as e:
        print(f"操作失败: {str(e)}")

if __name__ == "__main__":
    # 延迟10秒执行,确保Windows开机后网络已就绪
    time.sleep(10)
    start_remote_docker_containers()

3. 配置Windows开机自启

  • 将脚本保存为docker_auto_start.py
  • 创建批处理文件docker_start.bat,内容如下(替换脚本实际路径):
@echo off
python "C:\你的脚本存放路径\docker_auto_start.py"
exit
  • 按下Win + R输入shell:startup,打开Windows开机启动文件夹
  • 将docker_start.bat复制到该文件夹内

关键注意事项

  • 密码安全:禁止明文写入脚本,通过Windows系统环境变量REMOTE_SSH_PWD存储密码,避免泄露
  • 远程Docker状态:确保远程服务器的Docker服务已设置开机自启(Linux服务器执行systemctl enable docker)
  • 测试验证:手动运行脚本一次,确认能正常连接服务器并启动容器,再配置开机自启

内容的提问来源于stack exchange,提问作者harish

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 10:00:01