Connect to Azure VM via .Net 6 Web Api

Atanu Gupta 186 Reputation points
2023-06-07T08:34:08.8333333+00:00

Hello,

I am having a windows virtual machine in Azure which is inside a virtual network as usual. The VM is exposed via a public ip. Now I can comfortably RDP to that VM via that public ip and username/password from my local laptop.

The requirement is to connect to that VM via a .Net 6 Web API and execute a powershell script inside that VM and get the output of that. Is it anyway possible to connect to azure VM via API.

I have googled a lot but didn't found anything suitable or working. Or is it not possible at all.

Please advise. Any sample code would be highly appreciable.

Azure Virtual Machines
Azure Virtual Machines
An Azure service that is used to provision Windows and Linux virtual machines.
9,015 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Atanu Gupta 186 Reputation points
    2023-06-16T10:40:12.74+00:00

    Ok

    I have used the following code to connect to an Azure VM using AAD credentials and successfully executed a powershell script on it... and the requirement is resolved.

    Sharing the code if anybody need this kind of solution 😊

    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Azure.Management.Compute;
    using Microsoft.IdentityModel.Clients.ActiveDirectory;
    using Microsoft.Rest;
    
    ConnectVM()
    {
    	string TenantId = "";
    	string ApplicationId = "";
    	string SubscriptionId = "";
    	string ResourceGroup = "";
    	string VirtualMachineName = "";
    	string ClientSecret = "";
    	
    	var context = new AuthenticationContext($"https://login.microsoftonline.com/{TenantId}");	
    	var credentials = new ClientCredential(ApplicationId, ClientSecret);
    	var result = context.AcquireTokenAsync("https://management.azure.com/", credentials).Result;
    	
    	var token = result.AccessToken;
    	var tokencredentials = new TokenCredentials(token);
    	var computeClient = new ComputeManagementClient(tokencredentials)
    	{
    		SubscriptionId = SubscriptionId
    	};
    
    	var c = SdkContext.AzureCredentialsFactory.FromServicePrincipal(ApplicationId, ClientSecret, TenantId, AzureEnvironment.AzureGlobalCloud);
    
    	var azure = Azure.Configure()
    			.WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                .Authenticate(c)
                .WithSubscription(SubscriptionId);
    
    	// Get the VM reference
    	var virtualMachine = azure.VirtualMachines.GetByResourceGroup(ResourceGroup, VirtualMachineName);
    
    	if(virtualMachine != null)
    	{
    		// Define the script to execute
    		var scriptPath = "mypath/to/powershell/script.ps1";
    
    		var runCommandInput = new RunCommandInput()
    		{
    			CommandId = "RunPowerShellScript",
    			Script = new List<string> { System.IO.File.ReadAllText(scriptPath) },
    			Parameters = new List<RunCommandInputParameter>()
    		}
    
    		var runCommandResult = virtualMachine.RunCommand(runCommandInput);
    
    		//Retrieve the script execution output
    		var scriptOutput = runCommandResult.Value[0].Message;
    		return scriptOutput;
    	}
    	else
    	{
    		return "The VM is not found or there was an error connecting to it.";  
    	}
    }
    
    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.