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 ;

    }

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐