gpt4 book ai didi

java - 使用 SSHJ 连接到 AWS EC2 实例

转载 作者:太空宇宙 更新时间:2023-11-04 07:55:12 25 4
gpt4 key购买 nike

我在这方面遇到很多问题。

我有以下代码

            try {
final SSHClient ssh = new SSHClient();
PKCS8KeyFile keyFile = new PKCS8KeyFile();
keyFile.init(new File(Thread.currentThread().getContextClassLoader().getResource("development.pem").toURI()));
ssh.loadKnownHosts();
ssh.addHostKeyVerifier("ec2-XX-XX-XX-XX.compute-1.amazonaws.com", 22, "ff:59:aa:24:42:b1:a0:9f:c9:4c:73:34:fb:95:53:c2:b8:37:a8:f8");
// ssh.addHostKeyVerifier("ec2-XX-XX-XX-XX.compute-1.amazonaws.com", 22, "90:1e:4d:09:42:c4:16:8a:4c:dc:ae:c2:60:14:f9:ea");
ssh.connect("ec2-XX-XX-XX-XX.compute-1.amazonaws.com");
ssh.auth("ec2-user", new AuthPublickey(keyFile));
Session session = ssh.startSession();
Command sudo = session.exec("sudo su -");
System.out.println("sudo=" +sudo.getOutputAsString());
Command whoami = session.exec("whoami");
System.out.println("whoami=" + whoami.getOutputAsString());
} catch (Exception e) {
e.printStackTrace();
}

第一个 addHostKeyVerifier 使用 AWS 控制台上的指纹,注释掉的指纹是它一直告诉我它失败的指纹。我应该从哪里获取正确的 key 。

如果我使用第二个 key ,它会通过验证,然后会失败。

我使用的是 SSHJ 版本 0.8.1

最佳答案

这对我有用。

对于您的 PEM 文件,您需要使用 OpenSSHKeyFile key 提供程序。

  SSHClient ssh = new SSHClient();
OpenSSHKeyFile keyFile = new OpenSSHKeyFile();
File file = new File("c:\\full\\path\\to\\keyfile.pem");
keyFile.init(file);

就我个人而言,我只是禁止主机 key 验证以始终返回true。但我确信你的方法更安全(如果有效的话)。

  ssh.loadKnownHosts();
ssh.addHostKeyVerifier((a, b, c) -> true);

AWS 的用户名取决于您的镜像。很多时候它是“根”。就我而言,它是“ubuntu”。

  ssh.connect("ec2-54-165-233-48.compute-1.amazonaws.com");
ssh.auth("ubuntu", new AuthPublickey(keyFile));
Session session = ssh.startSession();

(注意:我使用的是 0.26.0 版本。)

关于java - 使用 SSHJ 连接到 AWS EC2 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13721867/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com