class SshUtil {

    public static String executeCommand( Session sessionObj, String command )
        throws JSchException, IOException
    {
        StringBuilder builder = null;
        logger.debug( "Starting to execute command [" + command + "]" );

        if ( sessionObj != null && command != null && !"".equals( command ) )
        {
            builder = new StringBuilder();
            Channel channel = null;

            int arrMaxSize = 1024;

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

                byte[] tmp = new byte[arrMaxSize];

                while ( true )
                {
                    while ( in.available() > 0 )
                    {
                        int i = in.read( tmp, 0, arrMaxSize );
                        if ( i < 0 )
                            break;
                        builder.append( new String( tmp, 0, i ) );
                    }

                    if ( channel.isClosed() )
                    {
                        break;
                    }
                    try
                    {
                        Thread.sleep( 500 );
                    }
                    catch ( Exception ee )
                    {

                    }
                }

                if ( channel.isClosed() && channel.getExitStatus() != 0 )
                {
                    logger.debug( "Command exited with error code " + channel.getExitStatus() );
                }
            }
            catch ( Exception e )
            {
                logger.error( "Received exception during command execution", e );
            }
            finally
            {
                if ( channel != null && channel.isConnected() )
                {
                    channel.disconnect();
                }
                logger.debug( "End of execution of command [" + command + "]" );
            }
            return builder.toString();
        }
        return null;
    }

}