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();    }}
新聞熱點
疑難解答