searchusermenu
  • 发布文章
  • 消息中心
点赞
收藏
评论
分享
原创

SSH Java客户端(sshj)操作简介

2023-11-16 06:49:40
829
0

一、sshj简介

SSHJ 与 JSch 一样,是 SSH 的一种 Java 实现,SSHJ 底层使用了 Apache SSHD,所以相对来说比 Apache SSHD 更易使用

二、引入sshj

        <dependency>
            <groupId>com.hierynomus</groupId>
            <artifactId>sshj</artifactId>
            <version>0.35.0</version>
        </dependency>

三、sshj使用简介

1、创建链接

//创建链接
        SSHClient sshClient = SSHJUtils.genSSHClient(linuxInfo.getUserName(), linuxInfo.getPassWord(), linuxInfo.getAddress());

2、上传文件

 // 上传文件
        SSHJUtils.doSFTPUpload(sshClient, cdPropertiesInfo.getJarFilePath(), "/tmp/");

3、执行命令

 // 重启服务
            List<String> commandList = Lists.newArrayList("rm -rf " + cdPropertiesInfo.getUploadFileDir() + "*.*",
                    "kill -9 " + pid,
                    "mv /tmp/" + cdPropertiesInfo.getJarFileName() + " " + cdPropertiesInfo.getUploadFileDir(),
                    "cd " + cdPropertiesInfo.getUploadFileDir(),
                    "nohup java -jar  " + cdPropertiesInfo.getJarFileName() + " --spring.profiles.active=" + cicdPropertiesInfo.getEnvName() + " >boot.log 2>&1 &");
            String result = SSHJUtils.doExecCommand(sshClient, commandList);

4、关闭ssh客户端

//关闭ssh客户端
        SSHJUtils.close(sshClient);

四、sshj工具类

import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.common.IOUtils;
import net.schmizz.sshj.connection.channel.direct.Session;
import net.schmizz.sshj.sftp.SFTPClient;
import net.schmizz.sshj.transport.verification.PromiscuousVerifier;
import net.schmizz.sshj.xfer.FileSystemFile;

import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * SSHJ工具类
 *
 * @DateTime: 7/28/23 9:43 AM
 **/
public class SSHJUtils {

    /**
     * 创建SSHJ连接
     *
     * @param userName
     * @param password
     * @param localIp
     * @return
     * @throws IOException
     */
    public static SSHClient genSSHClient(String userName, String password, String localIp) throws IOException {
        localIp = localIp.trim();
        SSHClient ssh = new SSHClient();
        //ssh.loadKnownHosts();
        // 跳过密钥验证
        ssh.addHostKeyVerifier(new PromiscuousVerifier());
        // 传入主机名或IP地址建立连接
        ssh.connect(localIp);
        // 通过用户名和密码进行验证
        ssh.authPassword(userName, password);
        return ssh;
    }

    /**
     * 创建Session
     *
     * @param sshClient
     * @return
     * @throws Exception
     */
    public static Session getSession(SSHClient sshClient) throws Exception {
        Session session = sshClient.startSession();
        return session;
    }

    /**
     * 执行命令
     *
     * @param sshClient
     * @param command
     * @return
     * @throws Exception
     */
    public static String doExecCommand(SSHClient sshClient, String command) throws Exception {
        Session session = getSession(sshClient);
        Session.Command cmd = session.exec(command);
        // 获取命令的执行结果
        String response = IOUtils.readFully(cmd.getInputStream()).toString();
        return response;
    }

    public static String doExecCommand(SSHClient sshClient, List<String> commands) throws Exception {
        return doExecCommand(sshClient, commands.stream().collect(Collectors.joining(";")));
    }

    /**
     * SFTP 上传文件
     *
     * @param ssh
     * @param localFilePath
     * @param remoteDirectory
     * @throws Exception
     */
    public static void doSFTPUpload(SSHClient ssh, String localFilePath, String remoteDirectory) throws Exception {
        try (SFTPClient sftp = ssh.newSFTPClient()) {
            sftp.put(new FileSystemFile(localFilePath), remoteDirectory);
        }
    }

    /**
     * SFTP 下载
     *
     * @param ssh
     * @param localFileDirectory
     * @param linuxFilePath
     * @throws Exception
     */
    public static boolean doSFTPDownload(SSHClient ssh, String localFileDirectory, String linuxFilePath) {
        try (SFTPClient sftp = ssh.newSFTPClient()) {
            sftp.get(linuxFilePath, localFileDirectory);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 关闭Sessiono
     *
     * @param session
     * @throws Exception
     */
    public static void close(Session session) throws Exception {
        if (Objects.nonNull(session)) {
            session.close();
        }
    }

    /**
     * 关闭客户端连接
     *
     * @param sshClient
     * @throws Exception
     */
    public static void close(SSHClient sshClient) throws Exception {
        if (Objects.nonNull(sshClient)) {
            sshClient.close();
        }
    }
}
0条评论
作者已关闭评论
孟****寅
44文章数
0粉丝数
孟****寅
44 文章 | 0 粉丝
原创

SSH Java客户端(sshj)操作简介

2023-11-16 06:49:40
829
0

一、sshj简介

SSHJ 与 JSch 一样,是 SSH 的一种 Java 实现,SSHJ 底层使用了 Apache SSHD,所以相对来说比 Apache SSHD 更易使用

二、引入sshj

        <dependency>
            <groupId>com.hierynomus</groupId>
            <artifactId>sshj</artifactId>
            <version>0.35.0</version>
        </dependency>

三、sshj使用简介

1、创建链接

//创建链接
        SSHClient sshClient = SSHJUtils.genSSHClient(linuxInfo.getUserName(), linuxInfo.getPassWord(), linuxInfo.getAddress());

2、上传文件

 // 上传文件
        SSHJUtils.doSFTPUpload(sshClient, cdPropertiesInfo.getJarFilePath(), "/tmp/");

3、执行命令

 // 重启服务
            List<String> commandList = Lists.newArrayList("rm -rf " + cdPropertiesInfo.getUploadFileDir() + "*.*",
                    "kill -9 " + pid,
                    "mv /tmp/" + cdPropertiesInfo.getJarFileName() + " " + cdPropertiesInfo.getUploadFileDir(),
                    "cd " + cdPropertiesInfo.getUploadFileDir(),
                    "nohup java -jar  " + cdPropertiesInfo.getJarFileName() + " --spring.profiles.active=" + cicdPropertiesInfo.getEnvName() + " >boot.log 2>&1 &");
            String result = SSHJUtils.doExecCommand(sshClient, commandList);

4、关闭ssh客户端

//关闭ssh客户端
        SSHJUtils.close(sshClient);

四、sshj工具类

import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.common.IOUtils;
import net.schmizz.sshj.connection.channel.direct.Session;
import net.schmizz.sshj.sftp.SFTPClient;
import net.schmizz.sshj.transport.verification.PromiscuousVerifier;
import net.schmizz.sshj.xfer.FileSystemFile;

import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * SSHJ工具类
 *
 * @DateTime: 7/28/23 9:43 AM
 **/
public class SSHJUtils {

    /**
     * 创建SSHJ连接
     *
     * @param userName
     * @param password
     * @param localIp
     * @return
     * @throws IOException
     */
    public static SSHClient genSSHClient(String userName, String password, String localIp) throws IOException {
        localIp = localIp.trim();
        SSHClient ssh = new SSHClient();
        //ssh.loadKnownHosts();
        // 跳过密钥验证
        ssh.addHostKeyVerifier(new PromiscuousVerifier());
        // 传入主机名或IP地址建立连接
        ssh.connect(localIp);
        // 通过用户名和密码进行验证
        ssh.authPassword(userName, password);
        return ssh;
    }

    /**
     * 创建Session
     *
     * @param sshClient
     * @return
     * @throws Exception
     */
    public static Session getSession(SSHClient sshClient) throws Exception {
        Session session = sshClient.startSession();
        return session;
    }

    /**
     * 执行命令
     *
     * @param sshClient
     * @param command
     * @return
     * @throws Exception
     */
    public static String doExecCommand(SSHClient sshClient, String command) throws Exception {
        Session session = getSession(sshClient);
        Session.Command cmd = session.exec(command);
        // 获取命令的执行结果
        String response = IOUtils.readFully(cmd.getInputStream()).toString();
        return response;
    }

    public static String doExecCommand(SSHClient sshClient, List<String> commands) throws Exception {
        return doExecCommand(sshClient, commands.stream().collect(Collectors.joining(";")));
    }

    /**
     * SFTP 上传文件
     *
     * @param ssh
     * @param localFilePath
     * @param remoteDirectory
     * @throws Exception
     */
    public static void doSFTPUpload(SSHClient ssh, String localFilePath, String remoteDirectory) throws Exception {
        try (SFTPClient sftp = ssh.newSFTPClient()) {
            sftp.put(new FileSystemFile(localFilePath), remoteDirectory);
        }
    }

    /**
     * SFTP 下载
     *
     * @param ssh
     * @param localFileDirectory
     * @param linuxFilePath
     * @throws Exception
     */
    public static boolean doSFTPDownload(SSHClient ssh, String localFileDirectory, String linuxFilePath) {
        try (SFTPClient sftp = ssh.newSFTPClient()) {
            sftp.get(linuxFilePath, localFileDirectory);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 关闭Sessiono
     *
     * @param session
     * @throws Exception
     */
    public static void close(Session session) throws Exception {
        if (Objects.nonNull(session)) {
            session.close();
        }
    }

    /**
     * 关闭客户端连接
     *
     * @param sshClient
     * @throws Exception
     */
    public static void close(SSHClient sshClient) throws Exception {
        if (Objects.nonNull(sshClient)) {
            sshClient.close();
        }
    }
}
文章来自个人专栏
行业动态-mdy
44 文章 | 1 订阅
0条评论
作者已关闭评论
作者已关闭评论
0
0