如何使用jsch以编程方式进行身份验证? [英] How do I authenticate programmatically using jsch?

查看:117
本文介绍了如何使用jsch以编程方式进行身份验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过sftp将文件上传到远程服务器.我正在使用Jsch库.下面的代码可以工作,但是即使我已在Session对象中设置了这些值,我也始终必须通过输出控制台输入用户名和密码.我在Stack Overflow和Jsch示例页面上看到的每个示例都需要用户输入.有没有办法以编程方式传递密码? (我需要通过用户名/密码进行身份验证.我无法使用SSH密钥...)

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

推荐答案

您需要添加以下代码:

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

谢谢

这篇关于如何使用jsch以编程方式进行身份验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆