我想在远程Windows机器上使用Java运行PowerShell命令,这实际上是打开入站防火墙端口。 script.ps1 包含以下命令
PowerShell cmd:- netsh advfirewall firewall add rule name="Open Port (8077)" dir=in action=allow protocol=TCP localport=(8077)
下面的代码在本地运行良好。但我只想从本地计算机在远程计算机上执行相同的操作,并且我无法手动执行任何操作(甚至无法在那里创建 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");
}
}
最佳答案
您的链接示例需要在远程虚拟机上启用 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/