@ Override public synchronized String executeCommand ( String command ) throws SshException { if ( ! isConnected ( ) ) { throw new IllegalStateException ( "Not connected!" ) ; } Channel channel = null ; try { logger . debug ( "Opening channel" ) ; channel = connectSession . openChannel ( CMD_EXEC ) ; ( ( ChannelExec ) channel ) . setCommand ( command ) ; ByteArrayOutputStream errOut = new ByteArrayOutputStream ( ) ; channel . setExtOutputStream ( errOut ) ; BufferedReader bufferedReader = new BufferedReader ( new InputStreamReader ( channel . getInputStream ( ) ) ) ; logger . debug ( "connecting channel." ) ; channel . connect ( ) ; // Seems like Gerrit does not like when you disconnect directly after the command has been sent. // For instance, we have seen effects of mails not being sent out. This is the reason for // receiving all the incoming data. String incomingLine = null ; StringBuilder commandOutput = new StringBuilder ( ) ; while ( ( incomingLine = bufferedReader . readLine ( ) ) != null ) { commandOutput . append ( incomingLine ) ; commandOutput . append ( ' ' ) ; logger . trace ( "Incoming line: {}" , incomingLine ) ; } logger . trace ( "Closing reader." ) ; bufferedReader . close ( ) ; // Exit code is only available if channel is closed, so wait a bit for it. // Channel.disconnect(), however, must not have been called yet. // See http://stackoverflow.com/questions/3154940/jsch-error-return-codes-not-consistent. waitForChannelClosure ( channel , CLOSURE_WAIT_TIMEOUT ) ; int exitCode = channel . getExitStatus ( ) ; if ( exitCode > 0 ) { String error = errOut . toString ( ) ; if ( error != null && error . trim ( ) . length ( ) > 0 ) { throw new SshException ( error . trim ( ) + " (" + String . valueOf ( exitCode ) + ")" ) ; } else { throw new SshException ( String . valueOf ( exitCode ) ) ; } } return commandOutput . toString ( ) ; } catch ( SshException ex ) { throw ex ; } catch ( JSchException ex ) { throw new SshException ( ex ) ; } catch ( IOException ex ) { throw new SshException ( ex ) ; } finally { if ( channel != null ) { logger . trace ( "disconnecting channel." ) ; channel . disconnect ( ) ; } } }
Execute an ssh command on the server . After the command is sent the used channel is disconnected .