Android:在JSch Channel上使用OutputStream和InputStream来传递SSH命令

时间:2016-04-13 14:45:28

标签: java android ssh inputstream jsch

我设法使用来自Jsch库的Exec Channel建立SSH连接,但我想使用Shell Channel,因为我需要对来自频道的反馈作出反应。我想我必须使用InputStream和OutputStream或者ByteArray I / O流。如何设置流然后编写和刷新outputStream不会做任何事情。也许我对如何使用i / o流缺乏了解。

到目前为止,代码如下所示:

这些对象在Activity

中声明
static Session session;
String sHost;
String sUser;
String sPassword;
boolean entered = false;
ChannelShell channelssh;
OutputStream commandStream;
InputStream resultStream;

调用它来启动会话,连接到服务器并打开Shell Channel:

@Override
public void onDialogPositiveClick(final String host, final String user, final String password) {
    sHost = host;
    sUser = user;
    sPassword = password;
    final Button connectButton = (Button)findViewById(R.id.connectSSH);
    final Button goButton = (Button)findViewById(R.id.startSSH);
    connectButton.setText("Connect!");

    new AsyncTask<Integer, Void, Void>() {
        @Override
        protected Void doInBackground(Integer... params) {
            try {
                JSch jsch = new JSch();
                session = jsch.getSession(sUser, sHost, 22);
                session.setPassword(sPassword);
                // Avoid asking for key confirmation
                Properties prop = new Properties();
                prop.put("StrictHostKeyChecking", "no");
                session.setConfig(prop);
                session.connect();
                channelssh = (ChannelShell) session.openChannel("shell");

                commandStream = new ByteArrayOutputStream();
                channelssh.setOutputStream(commandStream);
                byte[] tb = new byte[1024];
                resultStream = new ByteArrayInputStream(tb);
                channelssh.setInputStream(resultStream);
                channelssh.connect();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        protected void onPostExecute(Void v) {
            if(session != null) {
                if (session.isConnected()) {
                    goButton.setEnabled(true);
                    connectButton.setText("Disconnect");
                    toast("connected");
                } else {
                    toast("connection failed");
                }
            } else {
                toast("session not created");
            }
        }
    }.execute(1);

    entered = true;
    //dialog.dismiss();
}

然后,当我想传递一个我作为String的命令时,我想调用类似这样的东西

    public String executeRemoteCommand(String command) {
    try {
        commandStream.write(command.getBytes());
        commandStream.flush();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}

稍后这应该返回答案,但由于我甚至无法传递命令,因此我无法检查输出。有关如何使用InputStream传递答案的任何帮助都是相关的。

0 个答案:

没有答案