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:
/home/imam
imam
/home/imam
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:
specify the command on su
command-line, like the official JSch Sudo.java
example shows:
((ChannelExec)channel).setCommand("pbrun su - fclaim -c whoami");
or feed the command to the shell using its standard input:
OutputStream out = channel.getOutputStream();
out.write(("whoami\n").getBytes());
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).