Question

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) {
    }
Was it helpful?

Solution

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

OTHER TIPS

You can set up a factory with username and password and use that to create your session:

    final DefaultSftpSessionFactory factory = new DefaultSftpSessionFactory(true);
    factory.setHost(...);
    factory.setPort(...);
    factory.setUser(..);
    factory.setPassword(...);
    factory.setAllowUnknownKeys(true);
    final Session session = factory.getSession();

Take a look at Spring Integration, they have abstracted ftp into a messaging gateway which is quite nice (not going into more detail here as it's not directly related to the question)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top