jsch ssh服务器调用Linux命令或脚本的小问题

代码如下:

    public static boolean execshell(String command, String user, String passwd, String host) throws JSchException, IOException {  
        connect(user, passwd, host);
        BufferedReader reader = null;
        boolean flag = true;
        Channel channel = null;  
        String charset ="UTF-8";
        try {  
            //执行linux命令
            channel = session.openChannel("exec"); 
            ((ChannelExec) channel).setCommand(command);  
            ((ChannelExec) channel).setErrStream(System.err);  
            channel.connect(); 
            InputStream in = channel.getInputStream();
            reader = new BufferedReader(new InputStreamReader(in,
            Charset.forName(charset)));
            String buf = null;
            while ((buf = reader.readLine()) != null) {
            log.info(buf);
            }            
             }catch (Exception e) {
                 e.printStackTrace();
             }finally {   
                 reader.close();
                 channel.disconnect();  
                 session.disconnect();  
        }
        return flag;
    }

这里发现了一个问题,如果使用红色字体中的方法,用来输出执行linux命令或sh文件时系统错误的输出,这样的话会造成一个问题,就是使用log4j的方法无效,后面的log.info以及返回后其他类中的log都将失效,最终tomcat的catalina.out的日志就永远停止了。。。。所以使用时,一定要注释掉哦~或者不用哦~使用下面reader读取linux中的输出信息就行了哦~

原文地址:https://www.cnblogs.com/yangsy0915/p/5125982.html