仅在 JSch shell 通道中获取特定命令的输出

Get output of a specific command only in JSch shell channel

我正在尝试使用 JSch 在 java 中获取 shell 脚本的输出。执行 sudo 管理命令并获取脚本的输出。

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();
}

输出:

*ADMINSHELL* :/home/abcd # cd /logs
*ADMINSHELL* :/logs # 
*ADMINSHELL* :/logs # my script...
....
output goes here...
....

我怎样才能只得到这个 ADMINSHELL 的输出?例如,我只需要最终输出。我尝试使用如下检查,

for (String cmd : commands) {
    if(cmd.startsWith("for script")){
        shell.println(cmd);
    }

    try {
        Thread.sleep(2000);
    }
    catch (Exception e) {
    }
}

但是这次我遇到了一些权限被拒绝的问题。我只需要最后一个脚本的输出。

....
output goes here...
....

你必须读一些 buffer/string 的输出。然后解析出来,只打印你想要的部分。

参见How to get jsch shell command output in String

没有其他方法可以分离各个命令的输出。从 SSH 客户端的角度来看,shell 只是一个带有 input/output 的黑盒子。没有结构。


当您在脚本前后打印一些定界符时,它会有所帮助,例如:

echo ---begin---
/.../myscript.sh   
echo ---end---