jsch的完整使用-springboot项目

1、添加依赖

<!--linux连接shell依赖-->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.7.21</version>
        </dependency>
        <!-- jsch的方式 远程连接的包-->
        <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.55</version>
        </dependency>

2、工具类

/**
 * 执行Shell工具类
 *
 * @author JustryDeng
 * @date 2023/8/22 16:29
 */
@Slf4j
public class ExecuteShellUtil {
 

    /** 未调用初始化方法 错误提示信息 */
    private static final String DONOT_INIT_ERROR_MSG = "please invoke init(...) first!";
 
    private static Session session;
 

 
    private ExecuteShellUtil() {
    }
 
    /**
     * 获取ExecuteShellUtil类实例对象
     *
     * @return 实例
     * @date 2023/8/22 16:29
     */
    public static ExecuteShellUtil getInstance() {
        return new ExecuteShellUtil();
    }
 
    /**
     * 初始化
     *
     * @param ip
     *         远程Linux地址
     * @param port
     *         端口
     * @param username
     *         用户名
     * @param password
     *         密码
     * @throws JSchException
     *         JSch异常
     * @date 2023/8/22 16:29
     */
    public void init(String ip, Integer port, String username, String password) throws JSchException {
        JSch jsch = new JSch();

      //  jsch.getSession(username, ip, port);
        session = jsch.getSession(username, ip, port);
        session.setPassword(password);
        Properties sshConfig = new Properties();
        sshConfig.put("StrictHostKeyChecking", "no");
        session.setConfig(sshConfig);
        session.connect(1200 * 1000);


    }
 
    /**
     * 执行一条命令,探活使用
     */
    public static String execCmd(Session session,String command) throws Exception {
//        if (session == null || channel == null || channelExec == null) {
//            throw new Exception(DONOT_INIT_ERROR_MSG);
//        }
        // 打开执行shell指令的通道
        Channel channel = session.openChannel("exec");
        ChannelExec channelExec = (ChannelExec) channel;
        channelExec.setCommand("source /etc/profile && source ~/.bash_profile && source ~/.bashrc &&  adb devices && locale charmap");
        channelExec.setCommand(command);
        channel.setInputStream(null);
        channelExec.setErrStream(System.err);
       // channel.setXForwarding();
        channel.connect();



        StringBuilder sb = new StringBuilder(16);
        try (InputStream in = channelExec.getInputStream();
             InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
             BufferedReader reader = new BufferedReader(isr)) {
            String buffer;
            while ((buffer = reader.readLine()) != null) {
                sb.append("\n").append(buffer);
            }


         //2023-02-21 关闭流
            IoUtil.close(reader);
            IoUtil.close(isr);
            IoUtil.close(in);



            return sb.toString();
        }finally {
            if (channelExec.isConnected()) {
                channelExec.disconnect();
            }
            if (channel.isConnected()) {
                channel.disconnect();
            }
        }
    }


    /**
     * 执行一条命令
     */
    public String execCmd(String command) throws Exception {
//        if (session == null || channel == null || channelExec == null) {
//            throw new Exception(DONOT_INIT_ERROR_MSG);
//        }
        // 打开执行shell指令的通道
        Channel channel = session.openChannel("exec");
        ChannelExec channelExec = (ChannelExec) channel;
        channelExec.setCommand("source /etc/profile && source ~/.bash_profile && source ~/.bashrc &&  adb devices && locale charmap");
        channelExec.setCommand(command);
        channel.setInputStream(null);
        channelExec.setErrStream(System.err);
        // channel.setXForwarding();
        channel.connect();


        StringBuilder sb = new StringBuilder(16);
        try (InputStream in = channelExec.getInputStream();
             InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
             BufferedReader reader = new BufferedReader(isr)) {
            String buffer;
            while ((buffer = reader.readLine()) != null) {
                sb.append("\n").append(buffer);
            }


            //2023-02-21 关闭流
            IoUtil.close(reader);
            IoUtil.close(isr);
            IoUtil.close(in);





            return sb.toString();
        }finally {
            if (channelExec != null && channelExec.isConnected()) {
                channelExec.disconnect();
            }
            if ( channel != null && channel.isConnected()) {
                channel.disconnect();
            }
        }
    }





    /**
     * 执行一条命令 获取错误流中的内容
     */
    public String execCmdErrContent(String command) throws Exception {
//        if (session == null || channel == null || channelExec == null) {
//            throw new Exception(DONOT_INIT_ERROR_MSG);
//        }
        // 打开执行shell指令的通道
        Channel channel = session.openChannel("exec");
        ChannelExec channelExec = (ChannelExec) channel;
        channelExec.setCommand(command);
        channel.setInputStream(null);
        ByteArrayOutputStream err  = new ByteArrayOutputStream();
        channelExec.setErrStream(err);
        channel.connect();
        StringBuilder sb = new StringBuilder(16);
        try (InputStream in = channelExec.getErrStream();
             InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
             BufferedReader reader = new BufferedReader(isr)) {
            String buffer;
            while ((buffer = reader.readLine()) != null) {
                sb.append("\n").append(buffer);
            }



            //2023-02-21 关闭流
            IoUtil.close(reader);
            IoUtil.close(isr);
            IoUtil.close(in);
            IoUtil.close(err);



            if(StrUtil.contains(sb.toString(), "没有那个文件或目录")){
                return "";
            }else{
                return sb.toString();
            }

        }finally {
            if (channelExec != null && channelExec.isConnected()) {
                channelExec.disconnect();
            }
            if ( channel != null && channel.isConnected()) {
                channel.disconnect();
            }
        }
    }


    public static void closeConnect() {
        if (session != null && session.isConnected()) {
            session.disconnect();
        }
    }

3、使用方法

public static void createXml() {

        //初始化
        ExecuteShellUtil instance = ExecuteShellUtil.getInstance();
        String ls = "";

        //创建连接
        try {

            instance.init("172.161.28.51", 22, "root","root");


        //项目清除 1、clean 2、分析


//            ls = instance.execCmdErrContent("cat /opt/dmdbms/log/dm_DW1_01B_202203.log | grep -v 'INFO'");
//            String ls = instance.execCmd("cd /root/scan/pro;ls");
//            String ls2 = instance.execCmd("cd /root/scan/pro");

//            String ls = instance.execCmd("top -p 21475 -n 1 -b");
            ls = instance.execCmd("ls");


            if (!ObjectUtils.isEmpty(ls)) {
                throw new RuntimeException();
            }

        } catch (Exception e) {
           e.printStackTrace();
        }


        //返回的结果遍历
            List<String> lineFreedList = StrSplitter.splitByRegex(StrUtil.trimToEmpty(ls), "\n", -1, true, true);
            for (String s : lineFreedList) {
                List<String> stringList = StrSplitter.split(StrUtil.trimToEmpty(s), "=", -1, true, true);
                System.out.println(stringList);

            }



        return ;

    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
SpringBoot中集成JSch,你可以通过引入JSch库的Maven依赖来实现。引用提供了一个示例环境,其中包括了所需的JDK版本、Maven版本以及SpringBoot版本以及JSch版本。 你可以在pom.xml文件中添加以下依赖来引入JSch库: ```xml <!-- https://mvnrepository.com/artifact/com.jcraft/jsch --> <dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.55</version> </dependency> ``` 这将添加JSch库到你的项目中,允许你在后端代码中使用JSch来进行SSH连接、端口转发、文件传输等操作。可以参考引用中的Jsch百度百科介绍获取更多关于JSch的详细信息。 在SpringBoot中,你可以在后端框架中使用JSch来远程连接ECS服务器。你可以使用JSch提供的API来实现与服务器的交互。同时,可以结合其他工具或插件,如Websocket和xterm,来实现与前端的实时交互和终端显示器的渲染。引用提供了一些相关的博客地址供你参考。 因此,通过在SpringBoot项目中引入JSch依赖,并使用JSch提供的API,你可以实现SpringBoot集成JSch的功能。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [SpringBoot整合ssh](https://blog.csdn.net/Yan_kee/article/details/127263952)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [springboot + xterm.js + vue + websocket实现终端功能](https://download.csdn.net/download/qq_29777207/13584879)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值