Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I am trying to execute
multiple bash commands
through a Java program which connects to a SSH using JSch. But after
sudo
login, I am unable to execute any bash commands. From what I have read, after
sudo
login, we enter into a sub-shell. I wish to use a single channel. I am clueless as to what to do next.
ChannelExec chnlex=(ChannelExec) session.openChannel("exec");
InputStream in = chnlex.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(in));
chnlex.setCommand("sudo -u appbatch -H /opt/apptalk/local/bin/start_shell.sh -c <<exit");
chnlex.connect();
System.out.println("channel connection done");
String msg=null;
while((msg=br.readLine())!=null){
System.out.println(msg);
chnlex.disconnect();
System.out.println("channel disconnected");
Also could anyone tell me how to write these bash commands in a separate function or file?
The sudo
does not execute a new shell. But probably your start_shell.sh
script does. You probably refer to sudo su
. Maybe your script runs the su
?
Anyway, to provide commands to the shell, feed the commands using shell's standard input:
ChannelExec channel = (ChannelExec) session.openChannel("exec");
channel.setCommand("sudo su");
channel.connect();
OutputStream out = channel.getOutputStream();
out.write(("command1\n").getBytes());
out.write(("command2\n").getBytes());
out.flush();
The sudo
/su
are commands as any other, so it's actually the same as a very generic question:
Providing input/subcommands to command executed over SSH with JSch
Also see Running command after sudo login, which answers a more generic question on sudo su
, without an unclear use of some unknown shell script.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.