I am using file in which I passed below commands:
hostname
pwd
pbrun su - fclaim
whoami
cd ..
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:
- some hostname
/home/imam
- missing output
imam
- missing output
/home/imam
I had a similar issue and got it resolved with some help from
@Martin
, lot of R&D and scanning through SO links. Here is the program that worked for me.Output:
Your code executes each command in an isolated environment. So your second
whoami
does not run withinpbrun su
, as you probably hoped for.The
pbrun su
executes a new shell.To provide a command to the shell you either:
specify the command on
su
command-line, like the official JSchSudo.java
example shows:or feed the command to the shell using its standard input:
See also:
Executing multiple bash commands using a Java JSch program after sudo login and
Running command after sudo login.
In general, I recommend the first approach as it uses a better defined API (command-line argument).