SSHJ - Keypair login to EC2 instance

本秂侑毒 提交于 2019-11-27 14:30:46

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();
}

The example given for connecting to EC2 did not initially work for me until I added the BouncyCastleProvider to the java.security.Security class. The simple example that worked for me (written in Groovy for simplicity) is:

@Grab(group='net.schmizz', module='sshj', version='0.8.1')
@Grab(group='org.bouncycastle', module='bcprov-jdk16', version='1.46')

import net.schmizz.sshj.*
import net.schmizz.sshj.userauth.keyprovider.*
import net.schmizz.sshj.common.*
import net.schmizz.sshj.transport.verification.PromiscuousVerifier
import net.schmizz.sshj.connection.channel.direct.Session
import net.schmizz.sshj.connection.channel.direct.Session.Command

import java.security.*
import java.util.concurrent.TimeUnit

Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

client = new SSHClient()
client.addHostKeyVerifier(new PromiscuousVerifier())
client.connect("ec2-XXX-XXX-XXX-XXX.compute-1.amazonaws.com")

PKCS8KeyFile keyFile = new PKCS8KeyFile()
keyFile.init(new File("/dev/ec2/key/mykey.pem"))
client.authPublickey("ubuntu",keyFile) 

final Session session = client.startSession()
final Command cmd = session.exec("whoami")
String response = IOUtils.readFully(cmd.getInputStream()).toString()
cmd.join(10, TimeUnit.SECONDS)

println response   //ubuntu

session.close()
client.disconnect()

It's not the user authentication that's tripping you, it's the host key verification :)

Something like client.addHostKeyVerifier("xx:0a:xx:b5:c2:fd:44:1d:e0:e4:fc:xx:5f:f8:dd:f6") before connecting.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!