Java通过OpenSSH(ssh2/ScpClient)远程连接Windows10实现传输文件、解压缩包、执行命令等操作

环境准备

远程机器A:Windows 10 专业版 22H2
本地环境:jdk8

安装OpenSSH 服务

1、安装

设置 --> 应用 --> 应用和功能 --> 可选功能 --> 添加功能
在这里插入图片描述

在这里插入图片描述

由于我已经安装,在以安装功能里面即可找到。未安装的用户选择添加功能添加即可

2、开启服务

win + r 输入 services.msc

在这里插入图片描述

启动 OpenSSH SSH Server 服务

在这里插入图片描述

3、验证是否安装成功

输入ssh 出现如下提示即安装成功

C:\Users\SERVER>ssh
usage: ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-B bind_interface]
           [-b bind_address] [-c cipher_spec] [-D [bind_address:]port]
           [-E log_file] [-e escape_char] [-F configfile] [-I pkcs11]
           [-i identity_file] [-J [user@]host[:port]] [-L address]
           [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]
           [-Q query_option] [-R address] [-S ctl_path] [-W host:port]
           [-w local_tun[:remote_tun]] destination [command]

代码开发

1、pom文件引入

<dependency>
    <groupId>ch.ethz.ganymed</groupId>
    <artifactId>ganymed-ssh2</artifactId>
    <version>build210</version>
 </dependency>

2、OpenSshClient 工具类

package com.ncst;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.Objects;


/**
 * @Author: Lisy
 * @Date: 2023/05/30/14:44
 * @Description: ssh2工具类
 */
@Slf4j
public class OpenSshClient {

    private final String ip;
    private final int port;
    private final String username;
    private final String password;

    public OpenSshClient(String ip, int port, String username, String password) {
        this.ip = ip;
        this.port = port;
        this.username = username;
        this.password = password;
    }

    public OpenSshClient(String ip, String username, String password) {
        this.ip = ip;
        this.port = 22;
        this.username = username;
        this.password = password;
    }

    public void execCommand(String command) {
        Connection conn = new Connection(ip, port);
        Session sess = null;
        try {
            conn.connect();
            boolean isAuthenticated = conn.authenticateWithPassword(username, password);
            if (isAuthenticated) {
                log.info("【远程执行命令】:{} 连接成功,---执行命令:{}", ip, command);
            } else {
                log.info("【远程执行命令】:{} 连接失败,请检查用户密码是否正确", ip);
            }
            sess = conn.openSession();
            sess.execCommand(command);

            //回显信息
            InputStream is = new StreamGobbler(sess.getStdout());
            BufferedReader brs = new BufferedReader(new InputStreamReader(is));
            while (true) {
                String line = brs.readLine();
                if (line == null) {
                    break;
                }
                System.out.println(line);
            }
        } catch (IOException ex) {
            log.error(ex.getMessage(), ex);
        } finally {
            if (Objects.nonNull(sess)) {
                sess.close();
            }
            conn.close();
        }
    }

    public void getFile(String remoteFile, String localTargetDirectory) {
        Connection conn = new Connection(ip, port);
        try {
            SCPClient client = getScpClient(conn);
            client.get(remoteFile, localTargetDirectory);
            conn.close();
            log.info("【获取文件成功】{}:{}", ip, remoteFile);
        } catch (IOException ex) {
            log.error(ex.getMessage(), ex);
        }
    }

    /**
     * 上传文件
     * @param localFile             本地文件位置
     * @param remoteTargetDirectory 远程机器接收文件目录
     */
    public void putFile(String localFile, String remoteTargetDirectory) {
        Connection conn = new Connection(ip, port);
        try {
            SCPClient client = getScpClient(conn);
            client.put(localFile, remoteTargetDirectory);
            log.info("【文件远程上传】{} 上传成功", ip);
        } catch (IOException ex) {
            log.error(ex.getMessage(), ex);
        } finally {
            conn.close();
        }
    }

    /**
     * 上传文件并对远程机器上的文件重命名
     * @param localFile
     * @param remoteFileName
     * @param remoteTargetDirectory
     * @param mode
     */
    public void putFileRename(String localFile, String remoteFileName, String remoteTargetDirectory, String mode) {
        Connection conn = new Connection(ip, port);
        try {
            SCPClient client = getScpClient(conn);
            if ((mode == null) || (mode.length() == 0)) {
                mode = "0600";
            }
            client.put(localFile, remoteFileName, remoteTargetDirectory, mode);

            //重命名
            Session sess = conn.openSession();
            String tmpPathName = remoteTargetDirectory + File.separator + remoteFileName;
            String newPathName = tmpPathName.substring(0, tmpPathName.lastIndexOf("."));
            sess.execCommand("mv " + remoteFileName + " " + newPathName);

            log.info("【文件远程上传】{} 上传成功", ip);
        } catch (IOException ex) {
            log.error(ex.getMessage(), ex);
        } finally {
            conn.close();
        }
    }

    public void putFile(String localFile, String remoteFileName, String remoteTargetDirectory) {
        Connection conn = new Connection(ip, port);
        try {
            SCPClient client = getScpClient(conn);
            client.put(getBytes(localFile), remoteFileName, remoteTargetDirectory);
        } catch (IOException ex) {
            log.error(ex.getMessage(), ex);
        } finally {
            conn.close();
        }
    }

    /**
     * 将文件输入到字节数组
     *
     * @param filePath 文件路径
     * @return 字节数组
     */
    private byte[] getBytes(String filePath) {
        byte[] buffer = null;
        File file = new File(filePath);
        try (FileInputStream fis = new FileInputStream(file);
             ByteArrayOutputStream bos = new ByteArrayOutputStream(1024 * 1024)) {

            byte[] b = new byte[1024 * 1024];
            int i;
            while ((i = fis.read(b)) != -1) {
                bos.write(b, 0, i);
            }
            buffer = bos.toByteArray();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return buffer;
    }

    private SCPClient getScpClient(Connection conn) throws IOException {
        conn.connect();
        boolean isAuthenticated = conn.authenticateWithPassword(username, password);
        if (isAuthenticated) {
            log.info("【文件远程上传】{} 连接成功", ip);
        } else {
            log.error("【文件远程上传】{} 验证失败", ip);
        }

        return new SCPClient(conn);
    }

}

3、安装7z

编写 bat 脚本,在远程机器上面静默安装,命名为 install7z.bat

start /wait E:\\7z.exe /S

4、准备7z.exe 安装包

在官网下载

4、测试类

	/**
     * 传输压缩包和7z并在远程机器上面解压并执行命令
     */
     public static void main(String[] args) {
        OpenSshClient winClient = new OpenSshClient("192.168.22.40", 22, "Admin", "123456");
        String remoteDir = "E:\\";
        String fileName = "a.zip";

        // 传输7z.exe 和安装7z.exe脚本
        winClient.putFile("E:\\testTmp\\7z.exe", "7z.exe", remoteDir);
        winClient.putFile("E:\\testTmp\\install7z.bat", "install7z.bat", remoteDir);

        // 安装7z.exe
        winClient.execCommand(remoteDir + "install7z.bat");

        // 传输客户端
        winClient.putFile("E:\\testTmp\\" + fileName, fileName, remoteDir);
        // 解压脚本
        winClient.execCommand("C:\\\"Program Files\"\\7-Zip\\7z x E:\\a.zip -oE:\\");

        // 删除安装包
        winClient.execCommand("del E:\\a.zip");
        winClient.execCommand("del E:\\7z.exe");
    }
  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值