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

如何用Python在Azure虚拟机中运行监控脚本并自动关机

实现Azure VM中Bat进程监控与自动关机方案

核心思路

既然已经搞定VM启停,剩下的就是远程执行Bat脚本+监控进程状态+进程终止后触发关机,以下是几种实用方案:


方案一:用Azure Run Command远程监控(无需持续连接)

Azure自带的Run Command可以直接在VM上执行脚本,适合不需要一直保持远程会话的场景,用azure-mgmt-compute就能调用。

步骤1:启动Bat进程并记录PID

from azure.mgmt.compute import ComputeManagementClient
from azure.identity import DefaultAzureCredential

# 初始化Azure计算客户端
cred = DefaultAzureCredential()
compute_client = ComputeManagementClient(cred, "你的订阅ID")

# 提交PowerShell命令启动Bat并保存PID到文件
run_params = {
    "command_id": "RunPowerShellScript",
    "script": [
        "Start-Process -FilePath 'C:\\scripts\\你的脚本.bat' -PassThru | Select-Object -ExpandProperty Id | Out-File 'C:\\temp\\bat_pid.txt'"
    ]
}

# 执行命令到目标VM
compute_client.virtual_machines.run_command(
    resource_group_name="你的资源组名",
    vm_name="你的VM名",
    parameters=run_params
)

步骤2:定期检查进程状态,终止则关机

def check_bat_status():
    check_script = [
        "$pid = Get-Content 'C:\\temp\\bat_pid.txt'; if (Get-Process -Id $pid -ErrorAction SilentlyContinue) { 'Running' } else { 'Stopped' }"
    ]
    result = compute_client.virtual_machines.run_command(
        resource_group_name="你的资源组名",
        vm_name="你的VM名",
        parameters={"command_id": "RunPowerShellScript", "script": check_script}
    )
    return result.value[0].message.strip()

# 循环监控(比如每5分钟查一次)
import time
while True:
    status = check_bat_status()
    if status == "Stopped":
        # 调用已有的关机逻辑
        compute_client.virtual_machines.deallocate(
            resource_group_name="你的资源组名",
            vm_name="你的VM名"
        )
        break
    time.sleep(300)

方案二:WinRM/SSH远程会话监控(持续连接)

如果需要实时监控,用远程会话直接连VM,适合Windows用pywinrm,Linux用paramiko。

Windows VM示例(WinRM)

import winrm
import time
from azure.mgmt.compute import ComputeManagementClient
from azure.identity import DefaultAzureCredential

# 初始化Azure计算客户端(用于后续关机)
cred = DefaultAzureCredential()
compute_client = ComputeManagementClient(cred, "你的订阅ID")

# 建立WinRM连接
session = winrm.Session("VM的公网IP", auth=("VM用户名", "VM密码"))

# 启动Bat并获取PID
ps_cmd = "Start-Process -FilePath 'C:\\scripts\\你的脚本.bat' -PassThru | Select-Object -ExpandProperty Id"
result = session.run_ps(ps_cmd)
bat_pid = result.std_out.decode().strip()

# 持续监控进程
while True:
    check_result = session.run_ps(f"Get-Process -Id {bat_pid} -ErrorAction SilentlyContinue")
    # 进程不存在时,status_code会非0
    if check_result.status_code != 0:
        # 触发关机
        compute_client.virtual_machines.deallocate(
            resource_group_name="你的资源组名",
            vm_name="你的VM名"
        )
        break
    time.sleep(60)  # 每分钟检查一次

方案三:VM本地自行处理(最省心)

把监控和关机逻辑放到VM内部,不用远程盯着。写个Python脚本在VM里运行,启动Bat后等待它结束,然后自己触发关机。

VM内的监控脚本示例

import subprocess
from azure.mgmt.compute import ComputeManagementClient
from azure.identity import DefaultAzureCredential

# 启动Bat进程
bat_proc = subprocess.Popen(["C:\\scripts\\你的脚本.bat"])

# 等待Bat进程结束
bat_proc.wait()

# 进程结束后,调用Azure SDK关机
cred = DefaultAzureCredential()
compute_client = ComputeManagementClient(cred, "你的订阅ID")
compute_client.virtual_machines.deallocate(
    resource_group_name="你的资源组名",
    vm_name="你的VM名"
)

之后用远程命令启动这个脚本就行,VM自己跑完就关机,不用远程持续连接。


必备工具/库总结

  • azure-mgmt-compute:Azure官方SDK,负责所有VM操作(Run Command、启停)
  • pywinrm:Windows VM远程命令执行
  • paramiko:Linux VM SSH远程操作
  • subprocess:Python内置库,本地启动/监控进程(VM内用)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 08:10:32