Search code examples
javapowershellazureportwindows-firewall

run PowerShell command remotely using Java


I want to run a PowerShell command using Java on a remote windows machine, which is actually to open the inbound firewall port. script.ps1 contains the below command

PowerShell cmd:- netsh advfirewall firewall add rule name="Open Port (8077)" dir=in action=allow protocol=TCP localport=(8077)

enter image description here

The below code works fine locally. But I want to do same on a remote machine from my local machine only and I can't do anything manually (not even creating a ps1 file over there). I have admin rights on the remote computer.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class TestMain2 {

    public static void main(String[] args) throws IOException {
        String command = "powershell.exe \"C:\\Users\\Administrator\\Desktop\\agent_port\\script.ps1\"";

        // Executing the command
        Process powerShellProcess = Runtime.getRuntime().exec(command);
        // Getting the results
        powerShellProcess.getOutputStream().close();
        String line;
        System.out.println("Standard Output:");
        BufferedReader stdout = new BufferedReader(new InputStreamReader(powerShellProcess.getInputStream()));
        while ((line = stdout.readLine()) != null) {
            System.out.println(line);
        }
        stdout.close();
        System.out.println("Standard Error:");
        BufferedReader stderr = new BufferedReader(new InputStreamReader(powerShellProcess.getErrorStream()));
        while ((line = stderr.readLine()) != null) {
            System.out.println(line);
        }
        stderr.close();
        System.out.println("Done");

    }
}

I tried this link also :- Running Powershell script remotely through Java


Solution

  • Your link example needs enable Winrm Sevice on remotely VM. By default, Azure Windows VM does not allow winrm service. So, you could not use the example.

    For Azure VM, you could use Azure Custom Script Extension to do this.

    You could use this example. Add following code.

            //Add Azure Custom Script Extension
            windowsVM.update()
                .defineNewExtension("shuitest")
                .withPublisher("Microsoft.Compute")
                .withType("CustomScriptExtension")
                .withVersion("1.9")
                .withMinorVersionAutoUpgrade()
                .withPublicSetting("commandToExecute", "netsh advfirewall firewall add rule name=\"Open Port 8077\" dir=in action=allow protocol=TCP localport=8077")
                .attach()
            .apply();