java jsch 密钥登陆,密钥对登录与JSch EC2实例

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?

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值