使用 SDK 获取 Azure VM 的 IP

Get IP of Azure VM using SDK

我打开了一个 VM,运行 处于 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.模型
  • Microsoft.Azure.Management.Network

请注意,您必须在 nuget 搜索 window 中 select "Include Prerelease" 才能找到这些包。 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);

检索 Azure 虚拟机 public IP 地址的最简单方法是

{_VirtualMachineInstance}.GetPrimaryPublicIPAddress().IPAddress;

你可以在这里找到关于这件事的很好的解释- Tom Sun 的回答: