Desidero poter utilizzare la libreria SSH Java JSch per connettersi all'istanza EC2. Come utilizzo la mia coppia di chiavi .pem da AWS con JSch? Come faccio a gestire l'errore UnknownHostKey durante il tentativo di connessione?Accesso Keypair all'istanza EC2 con JSch
8
A
risposta
12
Il codice Groovy utilizzerà la libreria JSch per connettersi a un'istanza EC2, eseguire i comandi whoami e hostname, quindi stampare i risultati alla 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();
Ecco un altro esempio di come fare lo stesso collegamento, ma attraverso un tunnel SSH Gateway (NAT bastione): https://gist.github.com/scoroberts/5605655
3
1: copiare il file ec2.pem in ~/.ssh/
2: poi chmod 700 ~/.ssh/ec2.pem
3: creare un nuovo file ~/.ssh/config
vi ~/.ssh/config
Host ec2server1
HostName ec2.Server-Name.com
User ec2-user
IdentityFile "~/.ssh/ec2.pem"
4: Ora usare il comando con ssh e Host valore dato in prima linea/del file ~ .ssh/config. come questo
ssh ec2server1
5: Ora usare il comando passo 4 nel codice
domanda simile a http://stackoverflow.com/q/9283556/311525 ma con un'altra libreria – Scott