Java Code Examples for com.jcraft.jsch.ChannelExec#isClosed()

The following examples show how to use com.jcraft.jsch.ChannelExec#isClosed() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RemoteLauncherCommands.java    From gemfirexd-oss with Apache License 2.0 8 votes vote down vote up
/**
 * Connect to a remote host via SSH and execute a command.
 * 
 * @param host
 *          Host to connect to
 * @param user
 *          User to login with
 * @param password
 *          Password for the user
 * @param command
 *          Command to execute
 * @return The result of the command execution
 */
private Result executeSshCommand(final String host, final String user,
    final String password, final String command) {
  
  StringBuilder result = new StringBuilder();
  
  try {
    JSch jsch = new JSch();
    Session session = jsch.getSession(user, host, 22);
    session.setUserInfo(createUserInfo(password));
    session.connect(5000);

    ChannelExec channel = (ChannelExec) session.openChannel("exec");
    channel.setCommand(command);
    channel.setInputStream(null);
    channel.setErrStream(System.err);
    InputStream in = channel.getInputStream();

    channel.connect();

    byte[] tmp = new byte[1024];
    while (true) {
      while (in.available() > 0) {
        int i = in.read(tmp, 0, 1024);
        if (i < 0)
          break;
        result.append(new String(tmp, 0, i));
      }
      if (channel.isClosed()) {
        break;
      }
    }
    channel.disconnect();
    session.disconnect();
  } catch (Exception jex) {
    return createResult(Result.Status.ERROR, jex.getMessage());
  }
 
  return createResult(Result.Status.OK, result.toString());
}
 
Example 2
Source File: SshExecutor.java    From vividus with Apache License 2.0 6 votes vote down vote up
private String readChannelInputStream(ChannelExec channel) throws IOException
{
    try (InputStream in = channel.getInputStream();
            InputStreamReader reader = new InputStreamReader(in, StandardCharsets.UTF_8);
            StringWriter stringWriter = new StringWriter())
    {
        while (true)
        {
            IOUtils.copy(reader, stringWriter);
            if (channel.isClosed())
            {
                if (in.available() > 0)
                {
                    continue;
                }
                return stringWriter.toString();
            }
            Sleeper.sleep(Duration.ofSeconds(1));
        }
    }
}
 
Example 3
Source File: SSHPushWorker.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Wait for a given {@link ChannelExec} to be closed.
 * Will close channel if maxWait is set and exceeded.
 * @param channel the channel
 */
private void waitForChannelClosed(ChannelExec channel) {
    long startTime = System.currentTimeMillis();
    while (!channel.isClosed()) {
        // Check to see if we have been waiting too long, converts ms to minutes
        long elapsedTimeInMins =
                TimeUnit.MILLISECONDS.toMinutes(System.currentTimeMillis() - startTime);
        if (maxWait > 0 && elapsedTimeInMins > maxWait) {
            log.error("Task took too long to complete");
            channel.disconnect();
        }
        try {
            Thread.sleep(1000);
        }
        catch (InterruptedException e) {
            // Should not happen
        }
    }
}
 
Example 4
Source File: JschServiceImpl.java    From jwala with Apache License 2.0 5 votes vote down vote up
/**
 * Reads std and error remote output which are then wrapped inside {@link RemoteCommandReturnInfo}
 *
 * @param channelExec the channel where the command is sent for execution
 * @param timeout the length of time in ms in which the method waits for a available byte(s) as a result of command
 * @return {@link RemoteCommandReturnInfo}
 */
private RemoteCommandReturnInfo getExecRemoteCommandReturnInfo(final ChannelExec channelExec, final long timeout)
        throws IOException, JSchException {

    final String output = scrubberService.scrub(readExecRemoteOutput(channelExec, timeout));
    LOGGER.debug("remote output = {}", output);

    String errorOutput = null;

    // wait for the channel to close before checking the exit status
    final long startTime = System.currentTimeMillis();
    while (!channelExec.isClosed()) {
        if ((System.currentTimeMillis() - startTime) > CHANNEL_EXEC_CLOSE_TIMEOUT) {
            errorOutput = MessageFormat.format("Wait for channel to close timeout! Timeout = {0} ms",
                    CHANNEL_EXEC_CLOSE_TIMEOUT);
            LOGGER.error(errorOutput);
            break;
        }
    }

    LOGGER.debug("Channel exec exit status = {}", channelExec.getExitStatus());

    if (channelExec.getExitStatus() != 0 && channelExec.getExitStatus() != -1) {
        errorOutput = readExecRemoteOutput(channelExec, timeout);
        LOGGER.debug("remote error output = {}", errorOutput);
    }

    return new RemoteCommandReturnInfo(channelExec.getExitStatus(), output, errorOutput);
}
 
Example 5
Source File: RemoteLauncherCommands.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Connect to a remote host via SSH and execute a command.
 * 
 * @param host
 *          Host to connect to
 * @param user
 *          User to login with
 * @param password
 *          Password for the user
 * @param command
 *          Command to execute
 * @return The result of the command execution
 */
private Result executeSshCommand(final String host, final String user,
    final String password, final String command) {
  
  StringBuilder result = new StringBuilder();
  
  try {
    JSch jsch = new JSch();
    Session session = jsch.getSession(user, host, 22);
    session.setUserInfo(createUserInfo(password));
    session.connect(5000);

    ChannelExec channel = (ChannelExec) session.openChannel("exec");
    channel.setCommand(command);
    channel.setInputStream(null);
    channel.setErrStream(System.err);
    InputStream in = channel.getInputStream();

    channel.connect();

    byte[] tmp = new byte[1024];
    while (true) {
      while (in.available() > 0) {
        int i = in.read(tmp, 0, 1024);
        if (i < 0)
          break;
        result.append(new String(tmp, 0, i));
      }
      if (channel.isClosed()) {
        break;
      }
    }
    channel.disconnect();
    session.disconnect();
  } catch (Exception jex) {
    return createResult(Result.Status.ERROR, jex.getMessage());
  }
 
  return createResult(Result.Status.OK, result.toString());
}
 
Example 6
Source File: SftpFileSystem.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * Executes a command and returns the (standard) output through a StringBuilder.
 *
 * @param command The command
 * @param output  The output
 * @return The exit code of the command
 * @throws JSchException       if a JSch error is detected.
 * @throws FileSystemException if a session cannot be created.
 * @throws IOException         if an I/O error is detected.
 */
private int executeCommand(final String command, final StringBuilder output) throws JSchException, IOException {
    final ChannelExec channel = (ChannelExec) getSession().openChannel("exec");
    try {
        channel.setCommand(command);
        channel.setInputStream(null);
        try (final InputStreamReader stream = new InputStreamReader(channel.getInputStream())) {
            channel.setErrStream(System.err, true);
            channel.connect(connectTimeoutMillis);

            // Read the stream
            final char[] buffer = new char[EXEC_BUFFER_SIZE];
            int read;
            while ((read = stream.read(buffer, 0, buffer.length)) >= 0) {
                output.append(buffer, 0, read);
            }
        }

        // Wait until the command finishes (should not be long since we read the output stream)
        while (!channel.isClosed()) {
            try {
                Thread.sleep(SLEEP_MILLIS);
            } catch (final Exception ee) {
                // TODO: swallow exception, really?
            }
        }
    } finally {
        channel.disconnect();
    }
    return channel.getExitStatus();
}
 
Example 7
Source File: SftpFileSystemWindows.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
/**
 *
 * {@link  org.apache.commons.vfs2.provider.sftp.SftpFileSystem#executeCommand(java.lang.String, java.lang.StringBuilder) }
 */
private int executeCommand( String command, StringBuilder output ) throws JSchException, IOException {
  this.ensureSession();
  ChannelExec channel = (ChannelExec) this.session.openChannel( "exec" );
  channel.setCommand( command );
  channel.setInputStream( (InputStream) null );
  InputStreamReader stream = new InputStreamReader( channel.getInputStream() );
  channel.setErrStream( System.err, true );
  channel.connect();
  char[] buffer = new char[128];

  int read;
  while ( ( read = stream.read( buffer, 0, buffer.length ) ) >= 0 ) {
    output.append( buffer, 0, read );
  }

  stream.close();

  while ( !channel.isClosed() ) {
    try {
      Thread.sleep( 100L );
    } catch ( Exception exc ) {
      log.logMinimal( "Warning: Error session closing. " + exc.getMessage() );
    }
  }

  channel.disconnect();
  return channel.getExitStatus();
}
 
Example 8
Source File: JschServiceImpl.java    From jwala with Apache License 2.0 4 votes vote down vote up
/**
 * Read the remote output for the exec channel. This is the code provided on the jcraft site with a timeout added.
 *
 * @param channelExec the exec channel
 * @param timeout     the maximum period of time for reading the channel output
 * @return the output from the channel
 * @throws IOException for any issues encoutered when retrieving the input stream from the channel
 */
private String readExecRemoteOutput(ChannelExec channelExec, long timeout) throws IOException {
    final BufferedInputStream bufIn = new BufferedInputStream(channelExec.getInputStream());
    final StringBuilder outputBuilder = new StringBuilder();

    final byte[] tmp = new byte[BYTE_CHUNK_SIZE];
    final long startTime = System.currentTimeMillis();
    final long readLoopSleepTime = Long.parseLong(ApplicationProperties.get(
            JSCH_EXEC_READ_REMOTE_OUTPUT_LOOP_SLEEP_TIME.getPropertyName(), READ_LOOP_SLEEP_TIME_DEFAULT_VALUE));

    while (true) {
        // read the stream
        while (bufIn.available() > 0) {
            int i = bufIn.read(tmp, 0, BYTE_CHUNK_SIZE);
            if (i < 0) {
                break;
            }
            outputBuilder.append(new String(tmp, 0, i, StandardCharsets.UTF_8));
        }

        // check if the channel is closed
        if (channelExec.isClosed()) {
            // check for any more bytes on the input stream
            sleep(readLoopSleepTime);

            if (bufIn.available() > 0) {
                continue;
            }

            LOGGER.debug("exit-status: {}", channelExec.getExitStatus());
            break;
        }

        // check timeout
        if ((System.currentTimeMillis() - startTime) > timeout) {
            LOGGER.warn("Remote exec output reading timeout!");
            break;
        }

        // If for some reason the channel is not getting closed, we should not hog CPU time with this loop hence
        // we sleep for a while
        sleep(readLoopSleepTime);
    }
    return outputBuilder.toString();
}
 
Example 9
Source File: SshProvider.java    From parallec with Apache License 2.0 4 votes vote down vote up
/**
 * Seems there are bad naming in the library the sysout is in
 * channel.getInputStream(); the syserr is in
 * ((ChannelExec)channel).setErrStream(os);
 *
 * @param channel
 *            the channel
 * @return the response on singe request
 */
public ResponseOnSingeRequest executeAndGenResponse(ChannelExec channel) {
    ResponseOnSingeRequest sshResponse = new ResponseOnSingeRequest();

    InputStream in = null;
    OutputStream outputStreamStdErr = new ByteArrayOutputStream();
    StringBuilder sbStdOut = new StringBuilder();
    try {

        in = channel.getInputStream();
        channel.setErrStream(outputStreamStdErr);

        byte[] tmp = new byte[ParallecGlobalConfig.sshBufferSize];
        while (true) {
            while (in.available() > 0) {
                int i = in.read(tmp, 0, ParallecGlobalConfig.sshBufferSize);
                if (i < 0)
                    break;
                sbStdOut.append(new String(tmp, 0, i));

            }

            if (channel.isClosed()) {
                if (in.available() > 0)
                    continue;
                sshResponse.setFailObtainResponse(false);

                // exit 0 is good
                int exitStatus = channel.getExitStatus();
                sshResponse.setStatusCodeInt(exitStatus);
                sshResponse.setStatusCode(Integer.toString(exitStatus));
                break;
            }

            Thread.sleep(ParallecGlobalConfig.sshSleepMIllisBtwReadBuffer);
        }

        sshResponse.setResponseBody(sbStdOut.toString());
        sshResponse.setErrorMessage(outputStreamStdErr.toString());
        sshResponse.setReceiveTimeNow();
    } catch (Exception t) {
        throw new RuntimeException(t);
    }

    return sshResponse;
}