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?
Asked
Active
Viewed 1.2k times
11
-
similar question to http://stackoverflow.com/q/9283556/311525 but with a different library – Scott May 18 '13 at 16:37
2 Answers
19
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();
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
Scott
- 16,711
- 14
- 75
- 120
-
I'm trying to do the same , but what about when the '"/your path to your pem/gateway.pem"' is Encrypted ? it doesn't work :(:( ... – VitalyT Jun 07 '18 at 10:43
-
Read the docs (https://epaul.github.io/jsch-documentation/javadoc/). Try jsch.addIdentity(privateKey, "Passphrase"); – Scott Jun 14 '18 at 06:13
2
1: copy ec2.pem file to ~/.ssh/
2: then chmod 700 ~/.ssh/ec2.pem
3: create a new file ~/.ssh/config
vi ~/.ssh/config
Host ec2server1
HostName ec2.Server-Name.com
User ec2-user
IdentityFile "~/.ssh/ec2.pem"
4: Now use the command with ssh and Host value you given in ~/.ssh/config file's first line. like this
ssh ec2server1
5: Now use the step 4 command in your code
Scott
- 16,711
- 14
- 75
- 120
Sharad Chhetri
- 29
- 1