java - 使用 Java 远程运行 PowerShell 命令

标签 java powershell azure port windows-firewall

我想在远程Windows机器上使用Java运行PowerShell命令,这实际上是打开入站防火墙端口。 script.ps1 包含以下命令

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

enter image description here

下面的代码在本地运行良好。但我只想从本地计算机在远程计算机上执行相同的操作,并且我无法手动执行任何操作(甚至无法在那里创建 ps1 文件)。我拥有远程计算机的管理员权限。

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");

    }
}

我也尝试过此链接:- Running Powershell script remotely through Java

最佳答案

您的链接示例需要在远程虚拟机上启用 Winrm 服务。默认情况下,Azure Windows VM 不允许 winrm 服务。因此,您无法使用该示例。

对于 Azure VM,您可以使用 Azure Custom Script Extension来做到这一点。

你可以使用这个example 。添加以下代码。

        //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();

关于java - 使用 Java 远程运行 PowerShell 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47793246/

相关文章:

android - phone gap 安卓环境设置

java - 什么数据类型/类可以让我完成这个任务?

powershell - 从 redis-cli.exe --stat 获取值

powershell - 组合变量 - PowerShell

powershell - 将与模式匹配的行从文件夹中的所有文本文件提取到单个输出文件

java - 如何使用 MSI 从 Spring Boot 应用程序连接到 Azure key 保管库以进行本地开发

java - 在 Jackrabbit Repository 中存档文档的最佳方式是什么?

azure - 如何通过 Azure 数据工厂连接到 AutoSys

azure - AKS Azure 中的微服务与负载均衡器集成

azure - Windows Azure - 需要从内部停止 WorkerRole