javashellsshjsch

Executing sudo using SSH "exec" channel in JSch


I am using file in which I passed below commands:

  1. hostname
  2. pwd
  3. pbrun su - fclaim
  4. whoami
  5. cd ..
  6. pwd

Ad the Java code below:

for (String command1 : commands) {

    Channel channel=session.openChannel("exec");
    ((ChannelExec)channel).setCommand(command1);

    in=channel.getInputStream();
    channel.connect();
    byte[] tmp=new byte[1024];
    while(true){
      while(in.available()>0){
        int i=in.read(tmp, 0, 1024);
        if(i<0)
            break;
        System.out.println(new String(tmp, 0, i));
      }
      if(channel.isClosed()){
        break;
      }
    }
    channel.setInputStream(null);
    channel.disconnect();
}

But I'm getting this output:

  1. some hostname
  2. /home/imam
  3. missing output
  4. imam
  5. missing output
  6. /home/imam

Solution

  • Your code executes each command in an isolated environment. So your second whoami does not run within pbrun su, as you probably hoped for.

    The pbrun su executes a new shell.

    To provide a command to the shell you either:

    In general, I recommend the first approach as it uses a better defined API (command-line argument).