Reputation: 4562
I am trying to get the output of a shell script in java using JSch. Executing a sudo
admin command and get the output of a script.
Properties prop = new Properties();
InputStream input = null;
String host="myhost";
StringBuilder command1= new StringBuilder();
String userName = "root";
String password="password";
try{
JSch jsch = new JSch();
Session session = jsch.getSession(userName, host, 22);
session.setPassword(password);
session.connect();
System.out.println("Connected");
List<String> commands = new ArrayList<String>();
commands.add("ls");
commands.add("sudo myadmincmd");
commands.add("cd /logs");
commands.add("my script...");
Channel channel = session.openChannel("shell");
channel.connect();
channel.setOutputStream(System.out);
OutputStream os = channel.getOutputStream();
PrintStream shell = new PrintStream(os, true);
for (String cmd : commands) {
shell.println(cmd);
try {
Thread.sleep(2000);
}
catch (Exception ee) {
}
}
shell.println("exit");
shell.close();
channel.disconnect();
session.disconnect();
}catch(Exception e){
e.printStackTrace();
}
Output:
*ADMINSHELL* :/home/abcd # cd /logs
*ADMINSHELL* :/logs #
*ADMINSHELL* :/logs # my script...
....
output goes here...
....
How can I get the output of only this ADMINSHELL? For example I only need the final output. I tried using a check as below,
for (String cmd : commands) {
if(cmd.startsWith("for script")){
shell.println(cmd);
}
try {
Thread.sleep(2000);
}
catch (Exception e) {
}
}
But this time I am getting some permission denied issues. I need only the output of the last script.
....
output goes here...
....
Upvotes: 1
Views: 2947
Reputation: 202197
You have to read the output to some buffer/string. Then parse out and print only the part you want.
See How to get jsch shell command output in String.
There's no other way to separate output of individual commands. From an SSH client perspective, the shell is just a black box with input/output. There's no structure. The "shell" should not be use to automate command execution. You should use the "exec" channel. See also What is the difference between the 'shell' channel and the 'exec' channel in JSch.
In the "exec" channel, you execute each command independently, so you won't have problems separating their output. See How to read JSch command output?
Anyway, if you want to stick with your suboptimal "shell" solution, it helps, when you print some delimiter before and after the script like:
echo ---begin---
/.../myscript.sh
echo ---end---
Upvotes: 1