繁体   English   中英

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

[英]Unable to get response from a command (using 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();
        }

        }
    }

}

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

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

评论这一行,看看这里是否确实有东西。 另外,如何确定已连接? 设置命令的正确方法是这样,因此请执行以下操作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM