How do I authenticate programmatically using jsch?

≡放荡痞女 提交于 2020-04-12 18:04:38

问题


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

回答1:


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




回答2:


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)



来源:https://stackoverflow.com/questions/18835756/how-do-i-authenticate-programmatically-using-jsch

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!