gpt4 book ai didi

c# - 使用 SDK 获取 Azure VM 的 IP

转载 作者:行者123 更新时间:2023-12-03 01:50:43 26 4
gpt4 key购买 nike

我有一个虚拟机已启动并在 azure 中运行。我知道它的名称,但希望使用新的 C# SDK 以编程方式检索其 IP 地址并避免使用 REST API。我怎样才能做到这一点?

最佳答案

试试这个:

string subId = "deadbeef-beef-beef-beef-beefbeefbeef";
string resourceGroup = "SORG01";
string vmName = "SORG01-BOX01";

using (var client = new ComputeManagementClient(credentials))
{
client.SubscriptionId = subId;

VirtualMachine vm = VirtualMachinesOperationsExtensions.Get(client.VirtualMachines, resourceGroup, vmName);

networkName = vm.NetworkProfile.NetworkInterfaces[0].Id.Split('/').Last();
}

using (var client = new NetworkManagementClient(credentials))
{
client.SubscriptionId = subId;
var network = NetworkInterfacesOperationsExtensions.Get(client.NetworkInterfaces, resourceGroup, vmName);
string ip = network.IpConfigurations[0].PrivateIPAddress;
}

要拥有这些类,您需要从 nuget 安装:

  • Microsoft.Azure.Management.Compute
  • Microsoft.Azure.Management.Compute.Models
  • Microsoft.Azure.Management.Network

请注意,您必须在 nuget 搜索窗口中选择“包括预发布”才能找到这些软件包。 credentials 是一个 Microsoft.Rest.TokenCredentials 对象,您可以通过以下方式获取:

var authContext = new AuthenticationContext("https://login.windows.net/{YourTenantId}");
var credential = new ClientCredential("{YourAppID}", "{YourAppSecret}");
var result = authContext.AcquireTokenAsync("https://management.core.windows.net/", credential);

result.Wait();
if (result.Result == null)
throw new AuthenticationException("Failed to obtain the JWT token");

credentials = new TokenCredentials(result.Result.AccessToken);

关于c# - 使用 SDK 获取 Azure VM 的 IP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37575945/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com