无法为jsch运行exec

时间:2017-04-20 09:00:32

标签: unix ssh jsch

当我使用公钥运行grep for grep时,它失败并出现以下错误:

   Exception in thread "main" com.jcraft.jsch.JSchException: failed to send channel request

当我使用我的用户名密码运行相同的东西时它工作正常

以下是我的连接和运行命令方法

    public boolean validateUser(String host) throws Exception {
            logger.info("Validating user " + this.getUserId());
            String user = getUserId();

            JSch jsch = new JSch();
            try {

                session = jsch.getSession(user, host, 22);
                session.setConfig("PreferredAuthentications", "publickey");
                jsch.setKnownHosts("~/.ssh/known_hosts");
                jsch.addIdentity("~/.ssh/id_rsa");
                session.setConfig("StrictHostKeyChecking", "no");
                session.connect(30000);                 
                session.connect();

                return true;
            } catch (Exception e) {
                e.printStackTrace();
                logger.info("Exception" + e);
                throw e;
            }

        }

    public StringBuilder runCmd(String cmnd) throws JSchException, IOException {
             logger.info("connecting to server");
            Channel channel = this.session.openChannel("exec");
            ((ChannelExec) channel).setCommand(cmnd);
            channel.setXForwarding(true);
            ((ChannelExec) channel).setOutputStream(System.out);
            ((ChannelExec) channel).setErrStream(System.err);
            InputStream in = channel.getInputStream();

            channel.connect(500000);
            channel.setInputStream(System.in);
            BufferedInputStream bufIn = new BufferedInputStream(in);
            StringBuilder sb = new StringBuilder();
            byte[] tmp = new byte[1024];
            while (true) {

                while (bufIn.available() > 0) {
                    int i = bufIn.read(tmp, 0, 1024);
                    if (i < 0)
                        break;
                    sb.append((new String(tmp, 0, i)));

                }
                logger.info("channelStatus is " + channel.isClosed());
                logger.info("Exit status = " + channel.getExitStatus());
                if (channel.isClosed()) {
                    bufIn.close();
                    break;
                }
                while (channel.getExitStatus() == -1){
                    try{Thread.sleep(1000);}catch(Exception e){System.out.println(e);}
                 }
                logger.info("Closing unix connection");
            }
            channel.disconnect();
            return sb;
        }

0 个答案:

没有答案