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

如何通过Azure Function App定时触发Azure虚拟机上的可执行文件?

Azure Function 与 Azure VM 通信并触发执行可执行文件的方案

Azure Function 完全可以和 Azure VM 通信,能替代传统任务计划程序解决生产环境管理复杂、权限受限的问题,以下是可行的落地方案:

推荐方案:使用 Azure VM Run Command(原生安全,无需额外端口)

这是Azure官方推荐的方式,通过Azure Compute API直接在VM上执行命令,无需开放WinRM/SSH端口,权限可控,日志易管理。

实现步骤:

  1. 配置Function权限:给Function App启用系统分配托管标识,并为该标识分配虚拟机参与者角色(或更细粒度权限:Microsoft.Compute/virtualMachines/runCommand/action + Microsoft.Compute/virtualMachines/read),确保能访问目标VM。
  2. 设置Timer Trigger:创建Timer Trigger类型的Function,配置CRON表达式实现每日特定时间触发(比如0 0 9 * * *表示每天9点运行)。
  3. 编写Function代码调用Run Command:用Azure SDK调用Run Command API,执行VM上的可执行文件。

Python示例代码(Timer Trigger):

import azure.functions as func
from azure.mgmt.compute import ComputeManagementClient
from azure.identity import ManagedIdentityCredential

def main(mytimer: func.TimerRequest) -> None:
    # 用托管标识获取凭证
    credential = ManagedIdentityCredential()
    compute_client = ComputeManagementClient(credential, "你的订阅ID")
    
    # 配置VM信息
    resource_group = "VM所在资源组名称"
    vm_name = "目标VM名称"
    
    # Windows VM用RunPowerShellScript,Linux用RunShellScript
    command_params = {
        "command_id": "RunPowerShellScript",
        "script": [
            # 执行可执行文件的命令,按需修改路径
            'cmd.exe /c "C:\\Apps\\your-app.exe"'
        ]
    }
    
    # 执行命令并获取结果
    result = compute_client.virtual_machines.begin_run_command(
        resource_group, vm_name, command_params
    ).result()
    
    # 提取执行日志,可写入Log Analytics或存储账户
    execution_log = result.value[0].message
    print(f"执行输出: {execution_log}")

日志与权限优势:

  • 执行日志可在Azure Portal的VM -> Run Command页面查看,也可通过Function代码捕获后存入Azure Log Analytics,团队只需Log Analytics的查询权限即可查看,无需VM的直接访问权限。
  • 托管标识无需硬编码凭证,权限通过Azure RBAC精细控制,避免生产环境权限过度开放。

备选方案:远程执行(Windows WinRM / Linux SSH)

如果必须用远程方式,可通过Function建立WinRM(Windows)或SSH(Linux)连接执行命令,但需要开放对应端口,安全性不如Run Command,仅适合非生产或特殊场景:

  • Windows VM:启用WinRM,Function中用PowerShell或Python的pywinrm库远程执行命令。
  • Linux VM:配置SSH密钥,Function中用paramiko等库建立SSH连接执行命令。

额外优化:先启动VM再执行命令

如果目标VM可能处于停止状态,可在Function中先调用VM的启动API,等待VM运行后再执行可执行文件:

# 启动VM示例代码
compute_client.virtual_machines.begin_start(resource_group, vm_name).result()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 16:26:28