SSHJ - Keypair login to EC2 instance

前端 未结 3 2266
無奈伤痛
無奈伤痛 2020-12-03 12:59

I have a pem file that looks like the one in SSHJ tests (though I don\'t see it being referenced): https://github.com/shikhar/sshj/blob/master/src/test/resources/hostkey.pem

3条回答
  •  无人及你
    2020-12-03 13:01

    I have successfully connected to an Amazon EC2 instance using the following:

    final SSHClient ssh = new SSHClient();
    ssh.addHostKeyVerifier("XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX");
    
    ssh.connect("host");
    
    PKCS8KeyFile keyFile = new PKCS8KeyFile();
    keyFile.init(new File("server_pem.pem"));
    ssh.auth("ec2-user", new AuthPublickey(keyFile));
    
    try {
        final Session session = ssh.startSession();
        try {
            final Command command = session.exec("whoami");
            String response = IOUtils.readFully(command.getInputStream()).toString();
            command.join(10, TimeUnit.SECONDS);
            return response;
        } finally {
            session.close();
        }
    } finally {
        ssh.disconnect();
    }
    

提交回复
热议问题