1、目标windows机器开启winrm支持

  • 执行 winrm quickconfig 初始化WinRm
  • 执行命令 winrm set winrm/config/service/auth @{Basic=“true”} 配置登陆方式
  • 执行 winrm set winrm/config/service @{AllowUnencrypted=“true”} 配置加密方式

2、配置maven

<dependency>
  <groupId>io.cloudsoft.windows</groupId>
  <artifactId>winrm4j</artifactId>
  <version>0.5.0</version> <!-- WINRM4J_VERSION -->
</dependency>

3、编写测试类

public class WinRMHelper {

	private String ip;
	
	private String username;
	
	private String password;
	
	public static final int DEFAULT_PORT = 5985;
	
	public WinRMHelper(final String ip,final String username,final String password) {
		this.ip = ip;
		this.username = username;
		this.password = password;
	}
	
	public String execute(final String command) {
		WinRmClientContext context = WinRmClientContext.newInstance();
		WinRmTool tool = WinRmTool.Builder.builder(ip, username, password).setAuthenticationScheme(AuthSchemes.NTLM).port(DEFAULT_PORT).useHttps(false).context(context).build();
		tool.setOperationTimeout(5000L);
		WinRmToolResponse resp = tool.executeCommand(command);
		context.shutdown();
		return resp.getStdOut();
	}
	
	public static void main(String[] args) {
		WinRMHelper exec = new WinRMHelper("127.0.0.1","username","password");
		String resp = exec.execute("hostname");
		System.out.println(resp);
	}
	
}

4、参考