加密密钥后如何使用 Java 和 JSch 连接到远程 SSH 机器

How connect to remote SSH machine using Java with JSch when the key is encrypted

提到被问到的问题: Keypair login to EC2 instance with JSch

我正在尝试使用 JCraft JSch 连接到两台不同的 EC2 机器:

第一台没有对 .pem 文件进行加密的 EC2 机器,它运行完美!

$ cat ~/Documents/CA01.pem                                                                                       
-----BEGIN RSA PRIVATE KEY-----
…….

但是在第二台机器上 .pem 是加密的,我有一个密码:

$ cat ~/Documents/OPEN_VPN.pem                        
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info:……........

因此代码如下所示:

JSch jsch = new JSch();
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
config.put("PreferredAuthentications", "publickey,keyboard-interactive,password");
jsch.addIdentity("/path/to/pem/OPEN_VPN.pem");

session = jsch.getSession("root", getHost(), 22)
session.setConfig(config);
session.setPassword(getPsw());
session.connect(); // here I got Exception....

Channel channel = session.openChannel("sftp");
channel.connect();

我得到了:

Exception in thread "main" com.jcraft.jsch.JSchException: USERAUTH fail
    at com.jcraft.jsch.UserAuthPublicKey.start(UserAuthPublicKey.java:119)
    at com.jcraft.jsch.Session.connect(Session.java:470) ....

请帮忙。也许还有其他有用的库?

私钥密码不是会话密码。所以你不能将它传递给 Session.setPassword().

使用带密码短语的 JSch.addIdentity() 重载:

jsch.addIdentity("/path/to/pem/OPEN_VPN.pem", getPsw());

另请注意,私钥是否加密,与服务器无关。服务器不关心。因此,如果您对第一台服务器的私钥未加密感到满意,那么也没有理由对第二台服务器的私钥进行加密。只需删除加密。