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

求可触发Azure VM中PowerShell脚本的C# .NET6 Web API代码

.NET 6 Web API 触发Azure VM中的PowerShell脚本

前置依赖

先安装必要的NuGet包:

dotnet add package Azure.ResourceManager.Compute --version 1.0.0
dotnet add package Azure.Identity --version 1.10.3

配置设置

在appsettings.json中添加Azure相关配置项:

{
  "Azure": {
    "SubscriptionId": "你的订阅ID",
    "ResourceGroupName": "VM所在的资源组名称",
    "VmName": "目标VM的名称"
  }
}

实现Web API控制器

创建控制器类,通过Azure Compute SDK调用VM的RunCommand功能执行PowerShell脚本:

using Azure;
using Azure.Identity;
using Azure.ResourceManager.Compute;
using Azure.ResourceManager.Compute.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;

namespace VmScriptTriggerApi.Controllers;

[ApiController]
[Route("api/[controller]")]
public class VmScriptController : ControllerBase
{
    private readonly string _subscriptionId;
    private readonly string _resourceGroupName;
    private readonly string _vmName;

    public VmScriptController(IConfiguration configuration)
    {
        _subscriptionId = configuration["Azure:SubscriptionId"] ?? throw new ArgumentNullException(nameof(_subscriptionId));
        _resourceGroupName = configuration["Azure:ResourceGroupName"] ?? throw new ArgumentNullException(nameof(_resourceGroupName));
        _vmName = configuration["Azure:VmName"] ?? throw new ArgumentNullException(nameof(_vmName));
    }

    [HttpPost("run-script")]
    public async Task<IActionResult> RunPowerShellScript([FromBody] ScriptRequest request)
    {
        if (string.IsNullOrWhiteSpace(request.ScriptContent))
        {
            return BadRequest("脚本内容不能为空");
        }

        try
        {
            // 身份验证:本地开发用Azure CLI/VS登录信息,生产用托管标识
            var credential = new DefaultAzureCredential();
            var computeClient = new ComputeManagementClient(_subscriptionId, credential);

            // 构建脚本执行参数
            var runCommandInput = new RunCommandInput
            {
                CommandId = "RunPowerShellScript",
                Script = new List<string> { request.ScriptContent },
                Parameters = request.Parameters?.Select(p => new RunCommandInputParameter(p.Name, p.Value)).ToList()
            };

            // 远程执行脚本
            var response = await computeClient.VirtualMachines.RunCommandAsync(
                _resourceGroupName,
                _vmName,
                runCommandInput);

            // 解析执行结果
            var result = response.Value.Value.FirstOrDefault();
            if (result != null && result.ExitCode == 0)
            {
                return Ok(new
                {
                    Success = true,
                    Output = result.Message,
                    ExitCode = result.ExitCode
                });
            }
            else
            {
                return StatusCode(500, new
                {
                    Success = false,
                    Error = result?.Message ?? "脚本执行失败,未返回有效结果",
                    ExitCode = result?.ExitCode
                });
            }
        }
        catch (RequestFailedException ex)
        {
            return StatusCode((int)ex.Status, new
            {
                Success = false,
                Error = $"Azure API调用失败:{ex.Message}",
                ErrorCode = ex.ErrorCode
            });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new
            {
                Success = false,
                Error = $"执行出错:{ex.Message}"
            });
        }
    }

    // 请求模型类
    public class ScriptRequest
    {
        public string ScriptContent { get; set; } = string.Empty;
        public List<ScriptParameter>? Parameters { get; set; }
    }

    public class ScriptParameter
    {
        public string Name { get; set; } = string.Empty;
        public string Value { get; set; } = string.Empty;
    }
}

权限说明

  • 本地开发:确保你的Azure CLI/Visual Studio账号拥有目标VM所在资源组的Virtual Machine Contributor权限
  • 生产环境:给Web API所在的托管标识(如App Service托管标识)分配Virtual Machine Contributor角色到目标资源组或VM

使用示例

发送POST请求到https://<你的API地址>/api/vmscript/run-script,请求体示例:

{
  "ScriptContent": "Get-ChildItem C:\\",
  "Parameters": [
    {
      "Name": "Param1",
      "Value": "Value1"
    }
  ]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 23:47:10