我想通过sftp将文件上传到远程服务器。我正在使用Jsch库。下面的代码有效,但我总是要通过输出控制台输入用户名和密码,即使我在Session对象中设置了这些值。我在Stack Overflow和Jsch示例page上看到的每个例子都需要用户输入。有没有办法以编程方式传递密码? (我需要通过用户名/密码进行身份验证。我无法使用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) {
}
您需要添加以下代码:
jsch.addIdentity("<Key_path>"); // replace the key_path with actual value
session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");
谢谢
您可以使用用户名和密码设置工厂,并使用它来创建会话:
final DefaultSftpSessionFactory factory = new DefaultSftpSessionFactory(true);
factory.setHost(...);
factory.setPort(...);
factory.setUser(..);
factory.setPassword(...);
factory.setAllowUnknownKeys(true);
final Session session = factory.getSession();
看看Spring Integration,他们已经将ftp抽象为一个非常好的消息传递网关(这里没有详细介绍,因为它与问题没有直接关系)