使用 JSch 密钥对登录 EC2 实例 [英] Keypair login to EC2 instance with JSch

查看:24
本文介绍了使用 JSch 密钥对登录 EC2 实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够使用 JSch Java SSH 库连接到我的 EC2 实例.如何将来自 AWS 的 .pem 密钥对与 JSch 结合使用?尝试连接时如何处理 UnknownHostKey 错误?

I want to be able to use the JSch Java SSH library to connect to my EC2 instance. How do I use my .pem keypair from AWS with JSch? How do I deal with the UnknownHostKey error when attempting to connect?

推荐答案

groovy 代码将使用 JSch 库连接到 EC2 实例,运行 whoami 和 hostname 命令,然后将结果打印到控制台:

The groovy code will use the JSch library to connect to an EC2 instance, run the whoami and hostname commands, then print the results to the console:

@Grab(group='com.jcraft', module='jsch', version='0.1.49')

import com.jcraft.jsch.*

JSch jsch=new JSch();
jsch.addIdentity("/your path to your pem/gateway.pem");
jsch.setConfig("StrictHostKeyChecking", "no");

//enter your own EC2 instance IP here
Session session=jsch.getSession("ec2-user", "54.xxx.xxx.xxx", 22);
session.connect();

//run stuff
String command = "whoami;hostname";
Channel channel = session.openChannel("exec");
channel.setCommand(command);
channel.setErrStream(System.err);
channel.connect();

InputStream input = channel.getInputStream();
//start reading the input from the executed commands on the shell
byte[] tmp = new byte[1024];
while (true) {
    while (input.available() > 0) {
        int i = input.read(tmp, 0, 1024);
        if (i < 0) break;
        print(new String(tmp, 0, i));
    }
    if (channel.isClosed()){
        println("exit-status: " + channel.getExitStatus());
        break;
    }
    sleep(1000);
}

channel.disconnect();
session.disconnect();

这里是如何建立相同连接的另一个示例,但通过网关 ssh 隧道(NAT 堡垒):https://gist.github.com/scoroberts/5605655

Here's another example of how to make the same connection, but through a gateway ssh tunnel (NAT bastion): https://gist.github.com/scoroberts/5605655

这篇关于使用 JSch 密钥对登录 EC2 实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆