private static String launchACommand ( Session session , String command ) throws JSchException , IOException { Channel channel = session . openChannel ( "exec" ) ; ( ( ChannelExec ) channel ) . setCommand ( command ) ; channel . setInputStream ( null ) ; ( ( ChannelExec ) channel ) . setErrStream ( System . err ) ; InputStream in = channel . getInputStream ( ) ; channel . connect ( ) ; StringBuilder sb = new StringBuilder ( ) ; byte [ ] tmp = new byte [ 1024 ] ; while ( true ) { while ( in . available ( ) > 0 ) { int i = in . read ( tmp , 0 , 1024 ) ; if ( i < 0 ) break ; sb . append ( new String ( tmp , 0 , i ) ) ; } if ( channel . isClosed ( ) ) { if ( in . available ( ) > 0 ) continue ; System . out . println ( "exitstatus: " + channel . getExitStatus ( ) ) ; break ; } try { Thread . sleep ( 1000 ) ; } catch ( Exception ee ) { } } channel . disconnect ( ) ; String remoteResponseStr = sb . toString ( ) . trim ( ) ; return remoteResponseStr ; }
Launch a command on the remote host and exit once the command is done .