![](/img/trans.png)
[英]SSH password authentication in Java using jcraft JSch fails with "Auth fail" but command-line "ssh" works
[英]Java ssh connect with key using JSch - Auth Failed
我正在嘗試使用帶密鑰的 ssh 連接到本地主機,但我仍然收到“身份驗證失敗”錯誤。
下面是方法實現:
public void downloadUsingPublicKey(String username, String host)
{
String privateKey = "~/.ssh/id_rsa";
JSch jsch = new JSch();
Session session = null;
Channel channel = null;
ChannelSftp channelSftp = null;
try
{
jsch.addIdentity(privateKey);
System.out.println("Private Key Added.");
session = jsch.getSession(username, host);
System.out.println("session created.");
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
channel = session.openChannel("sftp");
channel.connect(); System.out.println("shell channel connected....");
channelSftp = (ChannelSftp)channel;
channelSftp.cd(Config.dir);
System.out.println("Changed the directory...");
} catch (JSchException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SftpException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}finally
{
if(channelSftp!=null)
{
channelSftp.disconnect();
channelSftp.exit();
}
if(channel!=null) channel.disconnect();
if(session!=null) session.disconnect();
}
}
我已經使用 linux 終端創建了我的公鑰/私鑰對,如下所示:
ssh-keygen -t rsa -b 4096 -C "myemail@email.com"
我沒有放任何詞組。 下一步:
ssh-add ~/.ssh/id_rsa
最后
cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys
然后當我運行我的程序時出現錯誤:
com.jcraft.jsch.JSchException: Auth fail
at com.jcraft.jsch.Session.connect(Session.java:512)
at com.jcraft.jsch.Session.connect(Session.java:183)
at pl.eroj.filedownloader.Downloader.downloadUsingPublicKey(Downloader.java:73)
at pl.eroj.filedownloader.Downloader.main(Downloader.java:107)
有任何想法嗎? 我的密鑰是 OpenSSH 類型的,以“-----BEGIN RSA PRIVATE KEY-----”行開頭
這是我如何使用私鑰路徑連接本地的
privateKeyPath ="C:\\Keys\\private_key.ppk"
public static OutputStream ConnectionUsingKey(String user, String hostName, String privateKeyPath)
throws JSchException, IOException {
JSch jsch = new JSch();
Session session = null;
try {
jsch.addIdentity(privateKeyPath);
session = jsch.getSession(user, hostName, 22);
session.setConfig("PreferredAuthentications", "publickey");
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
if (session.isConnected() == true) {
System.out.println("Connection to Session server is successfully");
}
channel = session.openChannel("shell");
channel.setInputStream(System.in);
channel.setOutputStream(System.out);
channel.connect(30 * 1000);
return channel.getOutputStream();
} catch (JSchException e) {
throw new RuntimeException("Failed to create Jsch Session object.", e);
}
}
謝謝@Vladi。 就我而言,我需要連接到同時使用私鑰和密碼的服務器。 因此我不得不像這樣設置配置
session.setConfig("PreferredAuthentications", "publickey,password");
session.setPassword("some_password");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.