How do I authenticate programmatically using jsch?

14,821

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

Share:
14,821
Ted
Author by

Ted

Updated on July 26, 2022

Comments

  • Ted
    Ted almost 2 years

    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) {
        }