简体   繁体   中英

Can I start a JSch session without a username and password?

I am using JSch in my Android app and I'd like to create a SSH connect without initially providing a username and password. I can connect if I provide a username and password, but I get a username is not given" error from JSch if I do not provide a username.

This is what I have tried to connect without providing the username and password.

private class ConnectSSH extends AsyncTask<Void, Void, String> {
    @Override
    protected String doInBackground(Void... a) {
        try {
            JSch jsch = new JSch();
            Session session = jsch.getSession("192.168.1.42");
            session.setPort(22);
            session.connect();
            Channel channelssh = (Channel)session.openChannel("exec");
            StringBuilder sb = new StringBuilder();
            InputStream commandOutput = channelssh.getInputStream();
            channelssh.connect();
            int readByte = commandOutput.read();
            while(readByte != 0xffffffff){
               sb.append((char)readByte);
               readByte = commandOutput.read();
            }
            channelssh.disconnect();
            return sb.toString();
        } catch (Exception e) {
            return "Error - " + e;
        }
    }
    @Override
    protected void onPostExecute(String result) {
        Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
    }
}

Will my only option be to change the source code of JSch to allow this, compile to a jar, and then import that?

The JSch Session class constructor needs to have the username filled.

But it's the UserAuth implementation that ultimately decides what username is used.

So you can extend for example UserAuthPassword to assign the actual username to .username field at the start of .start() method.

class UserAuthUsernamePassword extends UserAuthPassword {

  public boolean start(Session session) throws Exception {
    this.username = "real_username";
    return super.start(session);
  }

}

And you just pass a dummy value to username argument of Session constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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