import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UserInfo;

import org.apache.tools.ant.taskdefs.optional.ssh.SSHUserInfo;

import java.io.InputStream;

import java.lang.RuntimeException;

import java.nio.charset.Charset;


public class SSHExec {
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        if (args.length < 5) {
            throw new RuntimeException(
                "usage: SSHExec.jar <host> <username> <password> <command> <timeout(secs)>");
        }

        String host = args[0];
        String username = args[1];
        String password = args[2];
        String cmd = args[3];
        Double timeout = new Double(args[4]);
        boolean trust = true;

        /*                if(args.length==6) {
                                if(args[5].equalsIgnoreCase("-trust")) {
                                        trust = true;
                                }
                        }*/
        try {
            JSch jsch = new JSch();
            Session session = jsch.getSession(username, host, 22);
            session.setTimeout(timeout.intValue() * 1000);

            UserInfo ui = new SSHUserInfo(password, trust);
            session.setUserInfo(ui);
            session.connect();

            Channel channel = session.openChannel("exec");
            ((ChannelExec) channel).setCommand(cmd);
            //channel.setXForwarding(true);
            //channel.setInputStream(System.in);
            channel.setInputStream(null);
            ((ChannelExec) channel).setErrStream(System.err);

            InputStream in = channel.getInputStream();
            channel.connect();

            byte[] tmp = new byte[1024];
            String output = new String();

            while (true) {
                if (session.isConnected() == false) {
                    throw new RuntimeException("Connection Timed Out");
                }

                while (in.available() > 0) {
                    int i = in.read(tmp, 0, 1024);

                    if (i < 0) {
                        break;
                    }

                    output = output + new String(tmp, 0, i);

                    //		    		System.out.print(new String(tmp, 0, i));
                }

                if (channel.isClosed()) {
                    //		    			System.out.println("exit-status: "+channel.getExitStatus());
                    break;
                }

                try {
                    Thread.sleep(1000);
                } catch (Exception ee) {
                }
            }
            /*if(channel.getExitStatus()!=0) {
            	throw new Exception("Error: SSHExec command did not return 0 to the operating system.");
            }*/
            channel.disconnect();
            session.disconnect();
            System.out.print(output.replaceAll("\n", "\r\n"));
        } catch (Exception e) {
            System.err.println(e.getLocalizedMessage());
            System.exit(-1);
        }
    }
}
