0

我正在尝试从通过 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();
        }

        }
    }

}
4

1 回答 1

0

请检查您的 inputStream 是否实际可用。据我了解,问题是您的 inputStream 没有;没有给您任何东西,而不是

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

评论这一行,看看这里是否真的有什么东西。另外,您如何确定已连接?设置命令的正确方法是这样,所以请这样做:

 Channel channel=session.openChannel("exec");
  ((ChannelExec)channel).setCommand(command);
于 2013-03-05T13:16:56.823 回答