Java 如何使用 jsch 以编程方式进行身份验证?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18835756/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I authenticate programmatically using jsch?
提问by Ted
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 pagerequires user input. Is there a way to pass the password programmatically? (I am required to authenticate via username/password. I cannot use SSH keys...)
我想通过 sftp 将文件上传到远程服务器。我正在使用 Jsch 库。下面的代码有效,但我总是必须通过输出控制台输入用户名和密码,即使我已经在 Session 对象中设置了这些值。我在 Stack Overflow 和 Jsch 示例页面上看到的每个示例都需要用户输入。有没有办法以编程方式传递密码?(我需要通过用户名/密码进行身份验证。我不能使用 SSH 密钥......)
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) {
}
回答by Rajiv Kumar
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
谢谢
回答by Markoorn
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)
看一下 Spring Integration,他们将 ftp 抽象为一个非常好的消息网关(这里不详细介绍,因为它与问题没有直接关系)