java WinRM 远程连接 windows10 执行脚本

服务端环境配置

1、开启windows 远程管理

在这里插入图片描述
在这里插入图片描述

选择专用网络
在这里插入图片描述

点击确定退出

2、将网络类型修改成专用网络

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FRNIiNtS-1663211586894)(C:\Users\SERVER\OneDrive\桌面\work\img\image-20220915102922345.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-1GwY7fcj-1663211586894)(C:\Users\SERVER\OneDrive\桌面\work\img\image-20220915102939857.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-NUkga23g-1663211586894)(C:\Users\SERVER\OneDrive\桌面\work\img\image-20220915102956544.png)]
一般使用专用网络,不建议使用公用网络
文档地址
官方文档

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-YmwKVTGY-1663211586895)(C:\Users\SERVER\OneDrive\桌面\work\img\image-20220915104200620.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-HsggekB2-1663211586895)(C:\Users\SERVER\OneDrive\桌面\work\img\image-20220915104254282.png)]
鼠标右键重新启动

客户端连接

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

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值