Question

Scenario: 1.I am able to execute a bash script on remote ssh server successfully. 2.The script wants the user to enter some input's to proceed. The Program hangs after the script is executed. Q:1 Is this possible using JSCH or any other java based libraries? Q:2 Which is the best library in java to handle such scenario?

Below is my piece of code :

public class SshMultiCommands
{

public void execute(String u,String h,String p) throws Exception
   {
    JSch jsch = new JSch();
      String user = u;   
      String host = h; 
      String passwd = p;      
      int port = 22;   
      Session session = jsch.getSession(user, host, port);
      session.setPassword(passwd);

      session.setConfig("StrictHostKeyChecking", "no");

      session.connect();
      Channel channel = session.openChannel("shell");

      OutputStream ops = channel.getOutputStream();
      channel.setOutputStream(ops,true);
      ((ChannelShell)channel).setPtyType("vt102");
      ((ChannelShell)channel).setEnv("LANG", "ja_JP.eucJP");
      PrintStream ps = new PrintStream(channel.getOutputStream());
      channel.connect();

      Thread.sleep(1000);
      InputStream input = channel.getInputStream();
      //commands
      ps.println("ls -l");
      ps.println("bash /opt/dla.sh");
      ps.println("3"); // The sample user Input to script.This is getting printed but is not              getting executed

      printResult(input, channel);

      ps.close();

      channel.disconnect();
      session.disconnect();
      //System.out.println("OT Session Completed");
   }

    private static void printResult(InputStream input,
                                   Channel channel) throws Exception
   {
      int SIZE = 1024;
      byte[] tmp = new byte[SIZE];
      while (true)
      {
         while (input.available() > 0)
         {
            int i = input.read(tmp, 0, SIZE);
            if(i < 0)
               break;
             System.out.print(new String(tmp, 0, i));
         }
         if(channel.isClosed())
         {
            System.out.println("exit-status: " + channel.getExitStatus());
            break;
         }
         try
         {
            Thread.sleep(300);
         }
         catch (Exception ee)
         {
         }
      }
   }
}
Was it helpful?

Solution

Solution: Put sleep of 5-10 sec after you run the script or program. And keep flushing the output stream after every command. If you already used sleep, extend its time.

The program or script that u run takes a bit of time to take over the system's standard input and out streams. If u pass all the commands and params immediately the parameters which were intented for the program goes to the system's bash instead !

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top