Thursday 12 September 2013

Java Example to ssh to Unix box

I looked around for the sample code to connect to the unix box... I could find lot of examples but very few with private keys...and  found bit difficult to understand.
After spending some time.. I could found few examples to suit my requirement... so thought it might be helpful for someone else also...
I Referred conversion of private key from this link - http://www.tuxify.de/?p=519
Make sure you save the keys in .ssh format..

Here it goes---

package com.ssh;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringWriter;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelShell;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;



public class ConnectionTest {
public static void main(String[] arg) {
try {
JSch jsch = new JSch();

KeyPairGenerator keyPairGenerator = KeyPairGenerator
.getInstance("RSA");
keyPairGenerator.initialize(2048, new SecureRandom());
// PrivateKey privateKey =
// keyPairGenerator.genKeyPair().getPrivate();

StringWriter writer = new StringWriter();
// PEMWriter pemWriter = new PEMWriter(writer);

// pemWriter.writeObject(privateKey);

String privateKeyStr = writer.toString();

String user = "urusername";
String host = "ip address of the box u r trying to connect";
// ogre
// String host = "10.200.169.202";
int port = 22;
String privateKey = "key in ssh format";
String passphrase = "ur key's passphrase";
// jsch.addIdentity(privateKey);
jsch.addIdentity(privateKey, passphrase);

System.out.println("identity added ");
// addIdentity(String,bytearrayof ssh format file,null,byte array of
// passphrase file)
Session session = jsch.getSession(user, host, port);
System.out.println("session created. " + session);

java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setPassword("ur password");
System.out.println("before session connect");
session.connect();
System.out.println("session connected.....");

Channel channel = session.openChannel("shell");
channel.setInputStream(null);
channel.setOutputStream(null);

InputStream in = channel.getInputStream();
OutputStream out = channel.getOutputStream();

((ChannelShell) channel).setPtyType("vt102");
channel.connect();

byte[] tmp = new byte[1024];

out.write(("ls" + ";exit").getBytes());
out.write(("\n").getBytes());
out.flush();

while (true) {

while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0) {
// System.out.println("[debug] breaking at i < 0");
break;
}
String buffer = new String(tmp, 0, i);
String results = "";
// results.add(buffer);
// System.out.println("[debug]" + buffer);

System.out.println("result - " + buffer);
if (buffer.contains("REMOTE JSH COMMAND FINISHED")) {
System.out.println("[debug] breaking at finished");
break;
}
}
if (channel.isClosed()) {
// System.out.println("[debug] breaking at isClosed");
in.close();
break;
}
}
channel.disconnect();
session.disconnect();
} catch (Exception e) {
e.printStackTrace();
}

return;
}

// commented sftp code ...

/*
* Channel channel = session.openChannel("sftp");
* channel.setInputStream(System.in); channel.setOutputStream(System.out);
* channel.connect(); System.out.println("shell channel connected....");
*
* ChannelSftp c = (ChannelSftp) channel;
*
* String fileName = "D:/localfile.txt/test.txt";
* c.put(fileName, "./in/"); c.exit(); System.out.println("done");
*
* } catch (Exception e) { System.err.println(e); }
*/

}

Hope it helps :)


To copy the file and then delete from the unix box.. following code can be used--
Here, the session is the same variable which is created in the above code.. and logfileName is the file which needs to be copied...

public static void getLogBySftp(Session session, String  logFileName) throws JSchException, SftpException
{
Channel channel = session.openChannel("sftp");
channel.setInputStream(System.in); channel.setOutputStream(System.out);
channel.connect(); System.out.println("shell channel connected....");


//Channel channel = session.openChannel("sftp");
       ChannelSftp sftpChannel = (ChannelSftp) channel;
       System.out.println("Directory:" + sftpChannel.pwd());
      // sftpChannel.cd("remoteDirectory/");
       System.out.println("Directory after cd:" + sftpChannel.pwd());
       //sftpChannel.get( transactionId+".xml");
     
       System.out.println("xml file name  - "+logFileName);
       sftpChannel.get(logFileName, logFileName);

       sftpChannel.rm(logFileName);
     
       sftpChannel.exit();
}

No comments:

Post a Comment