Jsch处理命令确认是或否

时间:2019-04-30 14:36:52

标签: java linux jsch

我正在尝试使用Jsch的linux命令处理确认问题(y / n)。我能够在错误流中得到问题。但是在输出流中写入“ y”作为答案后,该命令没有得到它。我尝试使用的SAMPLE命令是'rm -i file1.txt',并且在写入'y'之后文件不会被删除。

我的目标命令在确认应从输入流读取的“ y”后也返回结果。回声y |目标命令对我来说不是一个选择。

        java.util.Properties config = new java.util.Properties();

        config.put("StrictHostKeyChecking", "no");
        JSch jsch = new JSch();
        Session session = jsch.getSession(user, host, 22);
        session.setPassword(password);
        session.setConfig(config);
        session.connect();
        System.out.println("Connected");

        System.out.println(command);
        ChannelExec channel = (ChannelExec) session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);
        channel.setInputStream(null);

        InputStream in = channel.getInputStream();
        OutputStream outChannel = channel.getOutputStream();
        InputStream errStream = channel.getErrStream();
        PrintWriter writer = new PrintWriter(outChannel);
        channel.connect();

        byte[] errTmp = new byte[1024];
        while (errStream.available() > 0) {
            int i = errStream.read(errTmp, 0, 1024);
            if (i < 0)
                break;
            sysout = new String(errTmp, 0, i);
            System.out.println("Error Line:"+sysout);
            if(sysout.toLowerCase().contains("remove regular file")) {
                writer.println("y"); // Works till here but not deleting file
            }
        }

        byte[] tmp = new byte[1024];
        while (true) {
            while (in.available() > 0) { 
                int i = in.read(tmp, 0, 1024);
                if (i < 0)
                    break;
                sysout = new String(tmp, 0, i);                 
                System.out.println(sysout);
            }
            if (channel.isClosed()) {
                System.out.println("exit-status: " + channel.getExitStatus());
                break;
            }
            try {
                Thread.sleep(1000);
            } catch (Exception ee) {
            }
            channel.disconnect();
        }
        session.disconnect();
        out.close();
        System.out.println("DONE");

1 个答案:

答案 0 :(得分:1)

Scanning files... Analyzing files... ERROR: UnusedVariable - foo.php:6:1 - Variable $a is never referenced $a = new A(); ------------------------------ 1 errors found ------------------------------ Checks took 0.27 seconds and used 67.096MB of memory Psalm was able to infer types for 100% of the codebase 除非被要求,否则不会自动刷新,因此,我相信您是在关闭频道之前从未实际发送过PrintWriter

您可以使用y构造函数创建一个PrintWriter,当调用println时将自动刷新。

我还认为您应该避免在等待结果的PrintWriter(OutputStream out, boolean autoflush)循环中调用channel.disconnect(),因为可以确保关闭频道后不会得到任何提示。