Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I authenticate programmatically using jsch?

Tags:

java

ssh

jsch

I want to upload a file to a remote server via sftp. I am using the Jsch library. The code below works, but I always have to enter the username and password via the output console, even though I've set those values in the Session object. Every example I've seen on Stack Overflow and on the Jsch example page requires user input. Is there a way to pass the password programmatically? (I am required to authenticate via username/password. I cannot use SSH keys...)

    JSch jsch = new JSch();
    ChannelSftp sftpChannel;
    Session session;
    Channel channel;
    OutputStream os;

    try {

        session = jsch.getSession("myUsername", "myHost", 22);
        session.setPassword("myPassword");
        session.setConfig("StrictHostKeyChecking", "no");
        session.connect();

        channel = session.openChannel("sftp");
        channel.connect();
        sftpChannel = (ChannelSftp) channel;
        os = sftpChannel.getOutputStream();

    } catch (Exception e) {
    }
like image 829
Ted Avatar asked Sep 16 '13 19:09

Ted


People also ask

Can we use JSch for SSH key based communication?

JSch is the Java implementation of SSH2 that allows us to connect to an SSH server and use port forwarding, X11 forwarding, and file transfer. Also, it is licensed under the BSD style license and provides us with an easy way to establish an SSH connection with Java.

What is JSch addIdentity?

addIdentity(String prvkey, String pubkey, byte[] passphrase) Adds an identity to be used for public-key authentication. protected void. addSession(Session session) Adds a session to our session pool.

What is Java JSch?

JSch is a pure Java implementation of SSH2. JSch allows you to connect to an sshd server and use port forwarding, X11 forwarding, file transfer, etc., and you can integrate its functionality into your own Java programs. JSch is licensed under BSD style license.


1 Answers

You need to add the below codes :

jsch.addIdentity("<Key_path>"); // replace the key_path with actual value
session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");

Thanks

like image 163
Rajiv Kumar Avatar answered Oct 22 '22 02:10

Rajiv Kumar