首页 > linux教程 > linux热点 阅读:0更新时间:2020-12-28 09:51:53

JSch连接linux

package cn.com.servyou.sdi.web.utils;

import cn.com.servyou.sdi.stream.SdiException;
import cn.com.servyou.sdi.web.vo.SshServer;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.Channelshell;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;

/**
 * java利用jsch远程连接linux进行管理
 **/
public class SSHUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(SSHUtils.class);
    public static Session getJschSession(SshServer sshServer) {
        JSch jsch = new JSch();
        try {
            Session session = jsch.getSession(sshServer.getSshServerUser(), sshServer.getSshServerUrl());
            session.setPassword(sshServer.getSshServerPassword());
            //第一次访问服务器不用输入yes
            session.setConfig("StrictHostKeyChecking", "no");
            session.setTimeout(60 * 60 * 1000);
            session.connect();
            return session;
        } catch (JSchException e) {
            LOGGER.error("连接SSH服务器失败", e);
            return null;
        }
    }
    public static String executeCommand(SshServer sshServer, String command) {
        // 执行单句命令
        Session session = getJschSession(sshServer);
        if (null == session) {
            throw new Exception("3", "登录SSH服务器失败");
        }
        String result = "";
        try {
            ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
            InputStream in = channelExec.getInputStream();
            channelExec.setCommand(command);
            channelExec.setErrStream(System.err);
            channelExec.connect();
            result = getResult(in, channelExec);
            channelExec.disconnect();
        } catch (JSchException | IOException e) {
            LOGGER.error("执行指令失败", e);
            throw new Exception("5", "执行指令失败");
        }
        session.disconnect();
        return result;
    }
    public static String executeShell(SshServer sshServer, String[] commands) {
        if (null == commands || commands.length == 0) {
            throw new Exception("12", "无指令");
        }
        String result = "";
        Session session = getJschSession(sshServer);
        if (null == session) {
            throw new Exception("00003", "登录SSH服务器失败");
        }
        try {
            ChannelShell channelShell = (ChannelShell) session.openChannel("shell");
            //从远端到达的数据  都能从这个流读取到
            InputStream inputStream = channelShell.getInputStream();
            channelShell.setPty(true);
            channelShell.connect();
            //写入该流的数据  都将发送到远程端
            OutputStream outputStream = channelShell.getOutputStream();
            PrintWriter printWriter = new PrintWriter(outputStream);
            for (String command : commands) {
                printWriter.println(command);
            }
            //把缓冲区的数据强行输出
            printWriter.flush();
            result = getResult(inputStream, channelShell);
            outputStream.close();
            inputStream.close();
            channelShell.disconnect();
        } catch (JSchException | IOException e) {
            LOGGER.error("执行指令失败", e);
        }
        session.disconnect();
        return result;
    }
    private static String getResult(InputStream in, Channel channel) throws IOException {
        StringBuilder sb = new StringBuilder();
        byte[] tmp = new byte[1024];
        while (!channel.isClosed()) {
            while (in.available() > 0) {
                int i = in.read(tmp, 0, 1024);
                if (i < 0) {
                    break;
                }
                sb.append(new String(tmp, 0, i));
            }
        }
        return sb.toString();
    }
}

beylze编程学院,一个分享编程知识和seo优化知识的网站。跟着beylze一起学习,每天都有进步。

通俗易懂,深入浅出,一篇文章只讲一个知识点。

文章不深奥,不需要钻研,在公交、在地铁、在厕所都可以阅读,随时随地涨姿势。

文章不涉及代码,不烧脑细胞,人人都可以学习。

当你决定关注beylze(公众号:beylze),你已然超越了90%的其他从业者!

相关文章

优秀教程