0

我正在使用这个我不完全理解的类(JSch),但我对它的工作原理有一个粗略的了解。如果 exitStatus 不是我想要的,我试图抛出一个异常。但是,使用

e.printStackTrace() or e.printStackTrace(System.err) //does nothing

e.printStackTrace(System.out) //prints the whole stack trace.

我以前从未见过这个问题,所以我想知道是我不理解的 API 导致了问题还是异常堆栈跟踪的工作方式不同?我有一种感觉,使用 apache log4j 会起作用,但我懒得仅仅为了测试目的而设置它,它不会回答为什么会发生这种情况的困惑。

如果有兴趣,这里是代码(我想在 exitStatus != 0 时抛出异常):

    Channel channel = null;
    int exitStatus = 1;
    System.out.println(command);
    try {
        channel = session.openChannel("exec");
        ChannelExec channelExec = (ChannelExec) channel;
        channelExec.setPty(true);
        channelExec.setCommand(command);
        channelExec.setInputStream(null);
        channelExec.setErrStream(System.err);
        InputStream in = channel.getInputStream();
        channel.connect();

        byte[] tmp=new byte[1024];
        int timeout = 0;
        while (true){
            while (in.available() > 0) {
                timeout = 0; // if read success, reset timeout
                int i = in.read(tmp, 0, 1024);
                if (i < 0)break;
                String status = new String(tmp, 0, i);
                /*System.out.println(status);*/
                if (status.toLowerCase().contains("incorrect password")) {
                    channel.disconnect();
                } else if (status.toLowerCase().contains("password")) {
                    OutputStream out = channel.getOutputStream();
                    out.write(args);
                    out.write('\n');
                    out.close();
                }
            }
            if (channel.isClosed()){
                exitStatus = channel.getExitStatus();
                break;
            }
            try { Thread.sleep(1000); } catch (Exception ee) { ee.printStackTrace(); }
            // nothing reads for 4 turns but stream is not closing, probably waiting for user input so exit
            if (timeout++ > 5) { 
                break;
            }
        }
    } catch (IOException ioe) {
        throw new ApplicationException(ioe);
    } catch (JSchException je) { 
        throw new ApplicationException("Could not create an exec channel for SSH. ", je);
    } finally {
        if (channel.isConnected()) channel.disconnect();
    }

  //if (exitStatus != 0) throw new MyCustomException(errormsg) 

谢谢。

4

0 回答 0