首頁 > 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%的其他從業者!

相關文章

優秀教程

国产亚洲欧美日韩