无法从命令获得响应(使用JSch)

时间:2013-03-05 12:40:30

标签: java android jsch

我正在尝试通过ssh发送的命令获得响应。我使用JSch lib连接。建立连接但从发送的命令中没有得到任何响应。

public void openSSH(
        String username,
        String password,
        String hostname,
        int port) throws Exception {     

    JSch jsch = new JSch();
    Session session = jsch.getSession(username, hostname, 22);
    this.session = session;
    session.setPassword(password);

    // Avoid asking for key confirmation
    Properties prop = new Properties();
    prop.put("StrictHostKeyChecking", "no");
    session.setConfig(prop);
    session.connect();

}

public String runCommand(String command)  throws Exception {
    // SSH Channel
    ChannelExec channelssh = (ChannelExec) session.openChannel("exec");      
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    InputStream in = channelssh.getInputStream();
    channelssh.setOutputStream(baos);

    // Execute command
    channelssh.setCommand(command);
    channelssh.connect();        



     System.out.println("Unix system connected...");
        byte[] tmp = new byte[1024];
        while (true){

            while (in.available() > 0) {
                Log.v("running", "line");  // won't work
                int i = in.read(tmp, 0, 1024);
                if (i < 0) {

                    break;
                }
                String line = new String(tmp, 0, i);
                System.out.println("Unix system console output: " +line);
                        channelssh.disconnect();
            }
        }
}



private class AsyncTaskOne extends AsyncTask<Void, Void, Boolean> {


    @Override
    protected Boolean doInBackground(Void... params) {

        try {
            openSSH("login", "pass", "10.10.10.80", 22 );
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        return true;
    }

    protected void onPostExecute(Boolean value) {

        if (value)  {
        try {
            runCommand("ls -llh");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        }
    }

}

1 个答案:

答案 0 :(得分:0)

请检查您的inputStream是否实际可用。根据我的理解,问题是您的inputStream没有提供任何内容而不是

 InputStream in = channelssh.getInputStream();
// channelssh.setOutputStream(baos); 

评论此行并查看此处是否存在实际内容。 你怎么确定你已经连接好了? 设置命令的正确方法是这样,请执行此操作:

 Channel channel=session.openChannel("exec");
  ((ChannelExec)channel).setCommand(command);