• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

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

武飞扬头像
AKA石头
帮助1

环境准备

远程机器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");
    }
学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhggajie
系列文章
更多 icon
同类精品
更多 icon
继续加载