Sco*_*ott 9 ssh jsch amazon-ec2
我希望能够使用JSch Java SSH库连接到我的EC2实例.如何在AWS中使用AWS的.pem密钥对?尝试连接时如何处理UnknownHostKey错误?
Sco*_*ott 16
groovy代码将使用JSch库连接到EC2实例,运行whoami和hostname命令,然后将结果打印到控制台:
@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();
Run Code Online (Sandbox Code Playgroud)
这是另一个如何建立相同连接的例子,但是通过网关ssh隧道(NAT堡垒):https://gist.github.com/scoroberts/5605655
| 归档时间: |
|
| 查看次数: |
9635 次 |
| 最近记录: |