0

Here is my code which logins to sftp server and executes command "dzdo su - ibmusr" command and changes the path of and folder and execute ls command. Here is the code

public class Sudo{
  public static void main(String[] arg) throws Exception{

      int port=22;
      String name ="john";
      String ip ="xxxx";
      String password ="root";

      JSch jsch = new JSch();
      Session session = jsch.getSession(name, ip, 22);
      session.setPassword(password);
      session.setConfig("StrictHostKeyChecking", "no");
      System.out.println("Establishing Connection...");
      session.connect();
      System.out.println("Connection established.");

      ChannelExec channelExec = (ChannelExec)session.openChannel("exec");

      InputStream in = channelExec.getInputStream();


      channelExec.setCommand("dzdo su - john");
      OutputStream out = channelExec.getOutputStream();
      out.write(("cd /xx.yy/zz \n").getBytes());

      out.write(("ls \n").getBytes());
      out.flush();
      channelExec.connect();

      BufferedReader reader = new BufferedReader(new InputStreamReader(in));
      String line;
      int index = 0;
      StringBuilder sb = new StringBuilder();
      while ((line = reader.readLine()) != null)
      {
          System.out.println(line);
      }
      session.disconnect();
  }
}

I am getting below exception

Exception in thread "main" java.io.IOException: failed to initialize the channel.
    at com.jcraft.jsch.Channel$1.init(Channel.java:242)
    at com.jcraft.jsch.Channel$1.write(Channel.java:253)
    at java.io.OutputStream.write(OutputStream.java:75)
    at com.consol.citrus.samples.todolist.Sudo.main(Sudo.java:43)
kushma gonna
  • 236
  • 3
  • 19

1 Answers1

1

Move the line

channelExec.connect();

above this block :

 OutputStream out = channelExec.getOutputStream();
 out.write(("cd /xx.yy/zz \n").getBytes());
 out.write(("ls \n").getBytes());
 out.flush();

Thereby you first establish the connection and then fetch the Output stream.

Nicholas K
  • 15,148
  • 7
  • 31
  • 57
  • Thank you the program is working fine but the program is not stopping – kushma gonna Oct 08 '18 at 17:13
  • Disconnect the channel and session. – Nicholas K Oct 08 '18 at 17:14
  • As I have [already wrote you before](https://chat.stackoverflow.com/transcript/message/44169585#44169585): *"Naturally, because the `su` keeps running. You have to send `exit` to close it."* – Martin Prikryl Oct 08 '18 at 17:16
  • Thank you the program is executing fine. – kushma gonna Oct 08 '18 at 17:21
  • I tried thos code moving the channeExcec.connect() like it was signaled and I replace `code`channelExec.setCommand("dzdo su - john");`code` by `code` channelExec.setCommand("whoami");`code`. And `code` out.write(("cd /xx.yy/zz \n").getBytes());`code` by code` out.write(("pwd").getBytes());`code` and only whoami output is display – sadati boina Feb 08 '22 at 15:23