Search in sources :

Example 96 with ChannelExec

use of com.jcraft.jsch.ChannelExec in project onos by opennetworkinglab.

the class SshUtil method executeCommand.

/**
 * Executes a given command. It opens exec channel for the command and closes
 * the channel when it's done.
 *
 * @param session ssh connection to a remote server
 * @param command command to execute
 * @return command output string if the command succeeds, or null
 */
public static String executeCommand(Session session, String command) {
    if (session == null || !session.isConnected()) {
        log.error("Invalid session({})", session);
        return null;
    }
    log.info("executeCommand: ssh command {} to {}", command, session.getHost());
    try {
        Channel channel = session.openChannel("exec");
        if (channel == null) {
            log.debug("Invalid channel of session({}) for command({})", session, command);
            return null;
        }
        ((ChannelExec) channel).setCommand(command);
        channel.setInputStream(null);
        InputStream output = channel.getInputStream();
        channel.connect();
        String result = CharStreams.toString(new InputStreamReader(output, StandardCharsets.UTF_8));
        log.trace("SSH result(on {}): {}", session.getHost(), result);
        channel.disconnect();
        return result;
    } catch (JSchException | IOException e) {
        log.debug("Failed to execute command {} due to {}", command, e);
        return null;
    }
}
Also used : JSchException(com.jcraft.jsch.JSchException) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) Channel(com.jcraft.jsch.Channel) IOException(java.io.IOException) ChannelExec(com.jcraft.jsch.ChannelExec)

Example 97 with ChannelExec

use of com.jcraft.jsch.ChannelExec in project onos by opennetworkinglab.

the class SshUtil method fetchLastTerm.

/**
 * Fetches last term after executing command.
 * @param session  ssh session
 * @param command command to execute
 * @return last term, or null
 */
public static String fetchLastTerm(Session session, String command) {
    if (session == null || !session.isConnected()) {
        log.error("Invalid session({})", session);
        return null;
    }
    log.info("fetchLastTerm: ssh command {} to {}", command, session.getHost());
    try {
        Channel channel = session.openChannel("exec");
        if (channel == null) {
            log.error("Invalid channel of session({}) for command({})", session, command);
            return null;
        }
        ((ChannelExec) channel).setCommand(command);
        channel.setInputStream(null);
        InputStream output = channel.getInputStream();
        channel.connect();
        String[] lineList = null;
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(output, StandardCharsets.UTF_8))) {
            lineList = reader.lines().findFirst().get().split(SPACESEPERATOR);
        } catch (IOException e) {
            log.error("Exception in fetchLastTerm", e);
        } finally {
            channel.disconnect();
            output.close();
        }
        if (lineList.length > 0) {
            return lineList[lineList.length - 1];
        } else {
            return null;
        }
    } catch (JSchException | IOException e) {
        log.error("Exception in fetchLastTerm", e);
        return null;
    }
}
Also used : JSchException(com.jcraft.jsch.JSchException) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) Channel(com.jcraft.jsch.Channel) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException) ChannelExec(com.jcraft.jsch.ChannelExec)

Example 98 with ChannelExec

use of com.jcraft.jsch.ChannelExec in project Jpom by dromara.

the class TestJschExec method test1.

@Test
public void test1() throws IOException, JSchException {
    Charset charset = CharsetUtil.CHARSET_UTF_8;
    Session session = JschUtil.createSession("192.168.1.8", 22, "root", "123456+");
    // session.connect();
    // ChannelExec channel = (ChannelExec) session.openChannel("exec");
    ChannelExec channel = (ChannelExec) JschUtil.createChannel(session, ChannelType.EXEC);
    // 添加环境变量
    channel.setCommand(cmd);
    InputStream inputStream = channel.getInputStream();
    InputStream errStream = channel.getErrStream();
    // channel.connect((int) TimeUnit.SECONDS.toMillis(5));
    channel.connect();
    // 
    final String[] error = new String[1];
    final String[] result = new String[1];
    try {
        System.out.println(error[0] = IoUtil.read(errStream, charset));
    } catch (Exception e) {
        e.printStackTrace();
        if (!StrUtil.contains(e.getMessage(), "Pipe closed")) {
            DefaultSystemLog.getLog().error("读取 exec err 流发生异常", e);
            error[0] = "读取 exec err 流发生异常" + e.getMessage();
        }
    }
    try {
        result[0] = IoUtil.read(inputStream, charset);
    } catch (Exception e) {
        e.printStackTrace();
        if (!StrUtil.contains(e.getMessage(), "Pipe closed")) {
            DefaultSystemLog.getLog().error("读取 exec 流发生异常", e);
            result[0] = "读取 exec 流发生异常" + e.getMessage();
        }
    }
    System.out.println("结束 " + result[0] + "  " + error[0]);
}
Also used : InputStream(java.io.InputStream) Charset(java.nio.charset.Charset) ChannelExec(com.jcraft.jsch.ChannelExec) IOException(java.io.IOException) JSchException(com.jcraft.jsch.JSchException) Session(com.jcraft.jsch.Session) Test(org.junit.Test)

Example 99 with ChannelExec

use of com.jcraft.jsch.ChannelExec in project Jpom by dromara.

the class TestJschExec method test.

@Test
public void test() throws IOException, JSchException {
    Charset charset = CharsetUtil.CHARSET_UTF_8;
    Session session = JschUtil.createSession("192.168.1.8", 22, "root", "123456+");
    ChannelExec channel = (ChannelExec) JschUtil.createChannel(session, ChannelType.EXEC);
    // 添加环境变量
    channel.setCommand(cmd);
    InputStream inputStream = channel.getInputStream();
    InputStream errStream = channel.getErrStream();
    channel.connect((int) TimeUnit.SECONDS.toMillis(5));
    // 
    SyncFinisher syncFinisher = new SyncFinisher(2);
    final String[] error = new String[1];
    final String[] result = new String[1];
    // 
    syncFinisher.addRepeatWorker(() -> {
        try {
            error[0] = IoUtil.read(errStream, charset);
        } catch (Exception e) {
            e.printStackTrace();
            if (!StrUtil.contains(e.getMessage(), "Pipe closed")) {
                DefaultSystemLog.getLog().error("读取 exec err 流发生异常", e);
                error[0] = "读取 exec err 流发生异常" + e.getMessage();
            }
        } finally {
            syncFinisher.stop();
        }
    }).addRepeatWorker(() -> {
        try {
            result[0] = IoUtil.read(inputStream, charset);
        } catch (Exception e) {
            e.printStackTrace();
            if (!StrUtil.contains(e.getMessage(), "Pipe closed")) {
                DefaultSystemLog.getLog().error("读取 exec 流发生异常", e);
                result[0] = "读取 exec 流发生异常" + e.getMessage();
            }
        } finally {
            syncFinisher.stop();
        }
    }).start();
    System.out.println(result[0] + "  " + error[0]);
}
Also used : SyncFinisher(cn.hutool.core.thread.SyncFinisher) InputStream(java.io.InputStream) Charset(java.nio.charset.Charset) ChannelExec(com.jcraft.jsch.ChannelExec) IOException(java.io.IOException) JSchException(com.jcraft.jsch.JSchException) Session(com.jcraft.jsch.Session) Test(org.junit.Test)

Aggregations

ChannelExec (com.jcraft.jsch.ChannelExec)99 InputStream (java.io.InputStream)63 IOException (java.io.IOException)59 JSchException (com.jcraft.jsch.JSchException)50 Channel (com.jcraft.jsch.Channel)48 Session (com.jcraft.jsch.Session)31 JSch (com.jcraft.jsch.JSch)29 FileInputStream (java.io.FileInputStream)26 InputStreamReader (java.io.InputStreamReader)26 BufferedReader (java.io.BufferedReader)23 OutputStream (java.io.OutputStream)22 File (java.io.File)17 Properties (java.util.Properties)16 FileOutputStream (java.io.FileOutputStream)15 ByteArrayOutputStream (java.io.ByteArrayOutputStream)7 SftpException (com.jcraft.jsch.SftpException)6 GFacException (org.apache.airavata.gfac.core.GFacException)6 ArrayList (java.util.ArrayList)5 Charset (java.nio.charset.Charset)4 UserInfo (com.jcraft.jsch.UserInfo)3