springboot封装linux交互工具类

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

1、pom.xml

<dependency>
			<groupId>com.jcraft</groupId>
			<artifactId>jsch</artifactId>
			<version>0.1.54</version>
</dependency>

2、 LinuxUtil.java

package net.wfl.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;

/**
 * linux操作常用工具类
 *
 * @author wangfenglei
 */
@Slf4j
public class LinuxUtil {
    /**
     * SSH连接端口
     */
    private static int SSH_PORT = 22;
    /**
     * SSH连接超时时间
     */
    private static int CONNECT_TIMEOUT = 30000;

    /**
     * 向linux发送命令
     *
     * @param username 用户名
     * @param password 密码
     * @param ip       IP
     * @param command  命令
     * @return 服务端响应字符串
     */
    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/wfl/opt/demo;sh demo.sh");
        log.info(msg);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值