服务端环境配置
1、开启windows 远程管理
选择专用网络
点击确定退出
2、将网络类型修改成专用网络
一般使用专用网络,不建议使用公用网络
官方文档
3、配置 WinRM
使用管理员权限
进入 PowerShell
#开启WinRM远程管理
Enable-PSRemoting –force
#设置WinRM自启动
Set-Service WinRM -StartMode Automatic
#对WinRM服务进行快速配置,包括开启WinRM和开启防火墙异常检测,默认的5985端口
winrm quickconfig
弹出选项输入 y
#为WinRM服务配置认证
winrm set winrm/config/service/auth '@{Basic="true"}'
#为WinRM服务配置加密方式为允许非加密:
winrm set winrm/config/service '@{AllowUnencrypted="true"}'
4、重启 winRM 服务
windows + R 输入 services.msc
鼠标右键重新启动
客户端连接
pom.xml
<dependency>
<groupId>io.cloudsoft.windows</groupId>
<artifactId>winrm4j</artifactId>
<version>0.12.3</version>
</dependency>
WinRMHelper
package com.info2soft.core.service.impl;
import io.cloudsoft.winrm4j.client.WinRmClientContext;
import io.cloudsoft.winrm4j.winrm.WinRmTool;
import io.cloudsoft.winrm4j.winrm.WinRmToolResponse;
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).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("192.168.26.45", "tom", "passsword");
String resp = exec.execute("hostname");
System.out.println(resp);
}
}
output
DESKTOP-4QSDB37