栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

springboot封装linux交互工具类

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot封装linux交互工具类

项目中用到linux交互,对此做了封装,作为工具类使用

1、pom.xml


			com.jcraft
			jsch
			0.1.54

2、 LinuxUtil.java

package net.grandhonor.framework.boot.util.util;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;

import java.io.InputStream;
import java.util.Properties;


@Slf4j
public class LinuxUtil {
    
    private static int SSH_PORT = 22;
    
    private static int CONNECT_TIMEOUT = 30000;

    
    public static String sendCommandToLinux(String username, String password, String ip, String command) {
        Session session = null;
        ChannelExec channel = null;
        InputStream inputStream = null;
        try {
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            //获取jsch的会话
            session = new JSch().getSession(username, ip, SSH_PORT);
            session.setConfig(config);
            //设置密码
            session.setPassword(password);
            //连接  超时时间30s
            session.connect(CONNECT_TIMEOUT);
            //开启shell通道
            channel = (ChannelExec) session.openChannel("exec");
            inputStream = channel.getInputStream();
            channel.setCommand(command);
            // 获取执行脚本可能出现的错误日志
            channel.setErrStream(System.err);
            channel.connect();
            String result = IOUtils.toString(inputStream, "UTF-8");
            return result;
        } catch (Exception e) {
            log.error(e.toString(), e);
        } finally {
            //断开连接后关闭会话
            session.disconnect();
            channel.disconnect();
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception e1) {
                    log.error(e1.toString(), e1);
                }
            }
        }

        return null;
    }

    public static void main(String[] args) {
        String msg = LinuxUtil.sendCommandToLinux("root", "root", "127.0.0.1", "cd /home/grandhonor/opt/demo;sh demo.sh");
        log.info(msg);
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/837845.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号