SSHJ - Keypair login to EC2 instance

前端 未结 3 2260
無奈伤痛
無奈伤痛 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();
    }
    
    0 讨论(0)
  • 2020-12-03 13:02

    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.

    0 讨论(0)
  • 2020-12-03 13:04

    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()
    
    0 讨论(0)
提交回复
热议问题