我有一个VM已启动并在azure中运行。我知道它的名字,但想要使用新的C#SDK以编程方式检索其IP地址并避免使用REST API。我怎么能这样做?
答案 0 :(得分:1)
试试这个:
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安装:
请注意,您必须在nuget搜索窗口中选择“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);
答案 1 :(得分:1)
检索Azure虚拟机公共IP地址的最简单方法是
{_ VirtualMachineInstance} .GetPrimaryPublicIPAddress()。IPAddress;
对此事的很好解释,您可以在这里找到-Tom Sun答案: