Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 仅在JSch shell通道中获取特定命令的输出_Java_Shell_Jsch - Fatal编程技术网

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

Java 仅在JSch shell通道中获取特定命令的输出,java,shell,jsch,Java,Shell,Jsch,我正在尝试使用JSch获得java中shell脚本的输出。执行sudoadmin命令并获取脚本的输出 Properties prop = new Properties(); InputStream input = null; String host="myhost"; StringBuilder command1= new StringBuilder(); String userName = "root"; String password="password"; try{ JSch

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

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的输出?例如,我只需要最终输出。我试着用下面的支票

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

    try {
        Thread.sleep(2000);
    }
    catch (Exception e) {
    }
}
但这次我遇到了一些被拒绝许可的问题。我只需要最后一个脚本的输出

。。。。
输出到这里。。。
....

您必须将输出读取到某个缓冲区/字符串。然后解析出来,只打印你想要的部分

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


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

echo---begin---
/…/myscript.sh
回音结束---