【发布时间】:2018-05-27 08:32:42
【问题描述】:
我想在远程windows机器上使用Java运行PowerShell命令,实际上是打开入站防火墙端口。 script.ps1 包含以下命令
PowerShell cmd:- netsh advfirewall firewall add rule name="Open Port (8077)" dir=in action=allow 协议=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");
}
}
【问题讨论】:
-
为什么要增加复杂性? PowerShell 通过
invoke-command(和其他方法)本机处理远程执行;用 Java 把它包起来只是自找麻烦。你怎么在远程机器上拥有管理员权限,但“在那里什么都做不了”? -
您的链接示例需要在远程服务中启用 winrm 服务。默认情况下,Azure Windows VM 不启用 winrm 服务。
-
@alroc 是的,我不能在那里手动做任何事情,因为我只能通过 java 代码来做。因为我们对此有一些业务需求。而且我也尝试了以下调用命令,但默认情况下未打开 5986 端口:- invoke-command -ComputerName "192.168.0.0" -filepath "C:\Users\Administrator\Desktop\agent_port\script.ps1 " -credential "密码"
-
远程服务需要打开winrm服务端口(598/5986)。
-
@Ankit4mjis 您可以使用 Azure 自定义脚本扩展来打开端口。我添加了如何执行此操作的示例。希望对您有所帮助。
标签: java powershell azure port windows-firewall