RichardSDetsch
asked on
How to construct an ssh tunnel inside a java program
How to have a java program do the same thing as the ssh unix command (0) where the userName does not have a password associated with it?
(0) The unix command that works
ssh -i ~/.ssh/pemFile.pem -L 8000:ec2-0-0-0-0.compute-1 .amazonaws .com:8000 userName@ec2-0-0-0-0.compu te-1.amazo naws.com
(1) The pem file
-----BEGIN RSA PRIVATE KEY-----
SOMETEXSOMETEXTALJDLAJFAJF LADSFJASDF FDA
ALDFJALFJASLDFASFDASJDLFJA SLDFJAJSSD LF
-----END RSA PRIVATE KEY-----
(2) Java program that currently does not work ( i think i need a user info object or something also I do not have both a cert and key in my pem file do I need to generate one of these?)
public static void main (String args []) throws Exception {
String pemPath = "/Users/username/.ssh/pemF ile.pem";
String ec2 = "userName@ec2-0-0-0-0.comp ute-1.amaz onaws.com" ;
SSLSocketFactory factory = null;
factory = getSocketFactoryPEM(pemPat h);
InetAddress remote = InetAddress.getByName(ec2) ;
InetAddress local = InetAddress.getByName("loc alhost");
Socket socket = factory.createSocket(remot e, 8000, local, 8000);
}
public static SSLSocketFactory getSocketFactoryPEM(String pemPath) throws Exception {
Security.addProvider(new BouncyCastleProvider());
SSLContext context = SSLContext.getInstance("TL S");
byte[] certAndKey = getBytesFromFile(new File(pemPath));
String delimiter = "-----BEGIN RSA PRIVATE KEY-----";
String[] tokens = new String(certAndKey).split(d elimiter);
byte[] certBytes = tokens[0].concat(delimiter ).getBytes ();
//byte[] keyBytes = tokens[1].getBytes();
PEMReader reader;
reader = new PEMReader(new InputStreamReader(new ByteArrayInputStream(certB ytes)));
X509Certificate cert = (X509Certificate)reader.re adObject() ;
//reader = new PEMReader(new InputStreamReader(new ByteArrayInputStream(keyBy tes)));
//PrivateKey key = (PrivateKey)reader.readObj ect();
KeyStore keystore = KeyStore.getInstance("JKS" );
keystore.load(null);
keystore.setCertificateEnt ry("cert-a lias", cert);
//keystore.setKeyEntry("ke y-alias", key, "changeit".toCharArray(), new Certificate[] {cert});
KeyManagerFactory kmf = KeyManagerFactory.getInsta nce("SunX5 09");
kmf.init(keystore, "changeit".toCharArray());
KeyManager[] km = kmf.getKeyManagers();
context.init(km, null, null);
return context.getSocketFactory() ;
}
(0) The unix command that works
ssh -i ~/.ssh/pemFile.pem -L 8000:ec2-0-0-0-0.compute-1
(1) The pem file
-----BEGIN RSA PRIVATE KEY-----
SOMETEXSOMETEXTALJDLAJFAJF
ALDFJALFJASLDFASFDASJDLFJA
-----END RSA PRIVATE KEY-----
(2) Java program that currently does not work ( i think i need a user info object or something also I do not have both a cert and key in my pem file do I need to generate one of these?)
public static void main (String args []) throws Exception {
String pemPath = "/Users/username/.ssh/pemF
String ec2 = "userName@ec2-0-0-0-0.comp
SSLSocketFactory factory = null;
factory = getSocketFactoryPEM(pemPat
InetAddress remote = InetAddress.getByName(ec2)
InetAddress local = InetAddress.getByName("loc
Socket socket = factory.createSocket(remot
}
public static SSLSocketFactory getSocketFactoryPEM(String
Security.addProvider(new BouncyCastleProvider());
SSLContext context = SSLContext.getInstance("TL
byte[] certAndKey = getBytesFromFile(new File(pemPath));
String delimiter = "-----BEGIN RSA PRIVATE KEY-----";
String[] tokens = new String(certAndKey).split(d
byte[] certBytes = tokens[0].concat(delimiter
//byte[] keyBytes = tokens[1].getBytes();
PEMReader reader;
reader = new PEMReader(new InputStreamReader(new ByteArrayInputStream(certB
X509Certificate cert = (X509Certificate)reader.re
//reader = new PEMReader(new InputStreamReader(new ByteArrayInputStream(keyBy
//PrivateKey key = (PrivateKey)reader.readObj
KeyStore keystore = KeyStore.getInstance("JKS"
keystore.load(null);
keystore.setCertificateEnt
//keystore.setKeyEntry("ke
KeyManagerFactory kmf = KeyManagerFactory.getInsta
kmf.init(keystore, "changeit".toCharArray());
KeyManager[] km = kmf.getKeyManagers();
context.init(km, null, null);
return context.getSocketFactory()
}
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
For the below how can I verify that a public key is in the remote ~/.ssh directoryIf it's not there how would this work?
(0) The unix command that works
You will have to upload your keys to the remote server and put it into the .ssh directory for the ssh connection to work to that server.
Regards,
Tomas Helgi
Regards,
Tomas Helgi
You will have to upload your keys to the remote server and put it into the .ssh directoryThat's already done (see my last comment)
In fact, it's conceivable you might have to do the reverse if you're using Jsch, as the load methods for keys seem to want to work only with a pair of files
ASKER
Thanks the below works and was derived form http://stackoverflow.com/questions/7525679/how-to-get-the-java-security-privatekey-object-from-rsa-privatekey-pem-from-a-f
public static void main (String args []) throws Exception {
String pemPath = "/Users/userName/.ssh/pemF ile.pem";
String ec2 = "ec2-xxxxxxxx-.compute-1.a mazonaws.c om";
Session session = connect(ec2, pemPath);
session.connect();
Thread.sleep(60000);
session.disconnect();
}
public static Session connect(String dnsName, String privKey) throws IOException {
JSch jSch = new JSch();
Session session = null;
try {
jSch.addIdentity(privKey);
session = jSch.getSession("someUser" , dnsName, 22);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyC hecking", "no");
session.setConfig(config);
System.out.println("Connec ting SSH to " + dnsName + " - Please wait for few minutes... ");
System.out.println("Forwar ding");
int assinged_port = session.setPortForwardingL (80, dnsName, 80);
System.out.println("localh ost:"+assi nged_port+ " -> "+dnsName+":80");
} catch (JSchException e) {
e.printStackTrace();
}
return session;
}
public static void main (String args []) throws Exception {
String pemPath = "/Users/userName/.ssh/pemF
String ec2 = "ec2-xxxxxxxx-.compute-1.a
Session session = connect(ec2, pemPath);
session.connect();
Thread.sleep(60000);
session.disconnect();
}
public static Session connect(String dnsName, String privKey) throws IOException {
JSch jSch = new JSch();
Session session = null;
try {
jSch.addIdentity(privKey);
session = jSch.getSession("someUser"
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyC
session.setConfig(config);
System.out.println("Connec
System.out.println("Forwar
int assinged_port = session.setPortForwardingL
System.out.println("localh
} catch (JSchException e) {
e.printStackTrace();
}
return session;
}
ASKER
Thanks the below works and was derived form http://stackoverflow.com/questions/7525679/how-to-get-the-java-security-privatekey-object-from-rsa-privatekey-pem-from-a-f
public static void main (String args []) throws Exception {
String pemPath = "/Users/userName/.ssh/pemF ile.pem";
String ec2 = "ec2-xxxxxxxx-.compute-1.a mazonaws.c om";
Session session = connect(ec2, pemPath);
session.connect();
Thread.sleep(60000);
session.disconnect();
}
public static Session connect(String dnsName, String privKey) throws IOException {
JSch jSch = new JSch();
Session session = null;
try {
jSch.addIdentity(privKey);
session = jSch.getSession("scbeCoreD evUsEast1" , dnsName, 22);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyC hecking", "no");
session.setConfig(config);
System.out.println("Connec ting SSH to " + dnsName + " - Please wait for few minutes... ");
System.out.println("Forwar ding");
int assinged_port = session.setPortForwardingL (8081, dnsName, 8080);
System.out.println("localh ost:"+assi nged_port+ " -> "+dnsName+":8080");
} catch (JSchException e) {
e.printStackTrace();
}
return session;
}
public static void main (String args []) throws Exception {
String pemPath = "/Users/userName/.ssh/pemF
String ec2 = "ec2-xxxxxxxx-.compute-1.a
Session session = connect(ec2, pemPath);
session.connect();
Thread.sleep(60000);
session.disconnect();
}
public static Session connect(String dnsName, String privKey) throws IOException {
JSch jSch = new JSch();
Session session = null;
try {
jSch.addIdentity(privKey);
session = jSch.getSession("scbeCoreD
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyC
session.setConfig(config);
System.out.println("Connec
System.out.println("Forwar
int assinged_port = session.setPortForwardingL
System.out.println("localh
} catch (JSchException e) {
e.printStackTrace();
}
return session;
}
Here are some examples to look at
http://www.example-code.com/java/ssh.asp
http://www.beanizer.org/site/index.php/en/Articles/Java-ssh-tunneling-with-jsch.html
Hope this helps.
Regards,
Tomas Helgi