密钥对登录与JSch EC2实例密钥、实例、JSch

2023-09-11 08:27:12 作者:爱我的请给花好么

我希望能够使用JSch Java的SSH文库连接到我的EC2实例。如何使用从AWS我的质子交换膜密钥对与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的code将使用JSch库连接到一个EC2实例,运行WHOAMI和主机名的命令,然后打印结果到控制台:

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();
 
精彩推荐
图片推荐