java通过winrm实现remote powershell
来源:https://github.com/cloudsoft/winrm4j
winrm4j is a project which enables Java applications to execute batch or PowerShell commands on a remote Windows server using WinRM
You can download the latest binaries here, which also gives the details for adding winrm4j as a dependency to your project.
If you wish to build the binaries yourself, you can clone this project, and build it using Maven:
winrm4j是一个使Java应用程序能够使用WinRM在远程Windows服务器上执行批处理或PowerShell命令的项目
您可以在此处下载最新的二进制文件,其中还提供了将winrm4j作为依赖项添加到项目中的详细信息。
如果您希望自己构建二进制文件,可以克隆此项目,并使用Maven进行构建:
mvn clean install
Maven dependency
Add the following to your pom.xml:
<dependency>
<groupId>io.cloudsoft.windows</groupId>
<artifactId>winrm4j</artifactId>
<version>0.13.0-SNAPSHOT</version>
</dependency>
Java client usage
To use winrm4j in Java code, you first create a WinRmTool object via the static WinRmTool.Builder class. WinRmTool.Builder has several options which you might consider setting before instantiating a WinRmTool:
Java客户端使用
要在Java代码中使用winrm4j,首先通过静态WinRmTool.Builder类创建WinRmTool对象。Builder有几个选项,您可以在实例化WilrMoToT之前考虑设置:
workingDirectory(String)
environment(Map<String,String>)
authenticationScheme(String)
disableCertificateChecks(boolean)
useHttps(boolean)
port(int)
A WinRmTool instance supports the basic executeCommand(String) method which executes windows native commands. Through executeCommand(String) method supports:
executeCommand(List<String>) execute a list of commands concatenated with &
executePs(String) execute a PowerShell command with the native windows command
executePs(List<String>) execute a list of PowerShell commands
WinRmClientContext context = WinRmClientContext.newInstance();
WinRmTool tool = WinRmTool.Builder.builder("my.windows.server.com", "Administrator", "pa55w0rd!")
.authenticationScheme(AuthSchemes.NTLM)
.port(5985)
.useHttps(false)
.context(context)
.build();
tool.executePs("echo hi");
context.shutdown();
WinRM 如何设置 TrustedHosts
如果希望 WinRM 能够建立连接,需要将 IP 地址设置为白名单。
查看当前 WinRM 的白名单
通过在命令行工具中运行下面的命令:
Get-Item WSMan:\localhost\Client\TrustedHosts
设置所有地址
下面的命令将会设置能够接受所有的配置。(双引号内可以设置ip)
Set-Item WSMan:\localhost\Client\TrustedHosts -Value '*'
添加到列表尾部
如果希望添加不同的地址到当前的信任列表中,但不修改当前的配置的话,需要使用关键字
-Concatenate
才可以。
例如可以使用下面的命令来进行添加。
Set-Item WSMan:\localhost\Client\TrustedHosts -Value 'machineC' -Concatenate
遇到问题及解决:
服务端winrm修改设置:
winrm set winrm/config/service '@{AllowUnencrypted="true"}'