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();
}

Monday, 24 October 2011

Learning from sickness

Looking back into 2011 year...
This year has brought lot of new things into me..

I started in january with new life and new place,
never thought how tough will be this phase,
felt lonelyness in home and could'nt keep up the pace,
ppl were different , place was different, and my work was just to chase,
i got some criticism managed some appreciation but lyf didnt stop for any of these
after few months i wanted to go home for vacation, my manager told me this should not be the case,
somehow after few arguments i went home for 3 weeks and thought lyf would be great after this phase,
but as always lyf has some different plans for you it has other surprises which u can not supress
so lyf gave me few shocks and i learnt how to deal with the unexpected knocks,
i extended my leave and rested in peace
when i came back i assumed everything's gonna be alright
but as you know lyf has some different plans
Last eight years watever i planned and lyf planned most of them were same
2011 was not the same
i came back, after few days i fell sick,
i thought here comes the lyf's another stick
again tried to learn how ppl will be feeling when they are ill,
in the end i realized all i am learning is how ppl feel about there pain,
but what i want i didnt gain.
hope lyf will gimme some gud surprises and i will back on track as ever
because lyf can not play and win with me always, as i m also very CLever



Tuesday, 17 August 2010

Final is not final anymore in java 1.5



I read somewhere about this concept.. This is very interesting ..  

Playing with your sanity - Strings

Have a look at the following code:
public class MindWarp {
  public static void main(String[] args) {
    System.out.println(
      "Romeo, Romeo, wherefore art thou oh Romero?");
  }
  private static final String OH_ROMEO =
    "Romeo, Romeo, wherefore art thou oh Romero?";
  private static final Warper warper = new Warper();
}
If we are told that the class Warper does not produce any visible output when you construct it, what is the output of this program? The most correct answer is, "you don't know, depends on what Warper does". Now THERE's a nice question for the Sun Certified Java Programmer Examination.
In my case, running "java MindWarp" produces the following output
C:> java MindWarp 
Stop this romance nonsense, or I'll be sick
And here is the code for Warper:
import java.lang.reflect.*;

public class Warper {
  private static Field stringValue;
  static {
    // String has a private char [] called "value"
    // if it does not, find the char [] and assign it to value
    try {
      stringValue = String.class.getDeclaredField("value");
    } catch(NoSuchFieldException ex) {
      // safety net in case we are running on a VM with a
      // different name for the char array.
      Field[] all = String.class.getDeclaredFields();
      for (int i=0; stringValue == null && i
        if (all[i].getType().equals(char[].class)) {
          stringValue = all[i];
        }
      }
    }
    if (stringValue != null) {
      stringValue.setAccessible(true); // make field public
    }
  }
  public Warper() {
    try {
      stringValue.set(
        "Romeo, Romeo, wherefore art thou oh Romero?",
        "Stop this romance nonsense, or I'll be sick".
          toCharArray());
      stringValue.set("hi there", "cheers !".toCharArray());
    } catch(IllegalAccessException ex) {} // shhh
  }
}
How is this possible? How can String manipulation in a completely different part of the program affect our class MindWarp?
To understand that, we have to look under the hood of Java. In the language specification it says in §3.10.5:
"Each string literal is a reference (§4.3) to an instance (§4.3.1, §12.5) of class String (§4.3.3). String objects have a constant value. String literals-or, more generally, strings that are the values of constant expressions (§15.28)-are "interned" so as to share unique instances, using the method String.intern."
The usefulness of this is quite obvious, we will use less memory if we have two Strings which are equivalent pointing at the same object. We can also manually intern Strings by calling the intern() method.
The language spec goes a bit further:
  1. Literal strings within the same class (§8) in the same package (§7) represent references to the same String object (§4.3.1).
  2. Literal strings within different classes in the same package represent references to the same String object.
  3. Literal strings within different classes in different packages likewise represent references to the same String object.
  4. Strings computed by constant expressions (§15.28) are computed at compile time and then treated as if they were literals.
  5. Strings computed at run time are newly created and therefore distinct.
  6. The result of explicitly interning a computed string is the same string as any pre-existing literal string with the same contents.
This means that if a class in another package "fiddles" with an interned String, it can cause havoc in your program. Is this a good thing? (You don't need to answer ;-)
Consider this example
public class StringEquals {
public static void main(String[] args) {
  System.out.println("hi there".equals("cheers !"));
}
private static final String greeting = "hi there";
private static final Warper warper = new Warper();
}
Running this against the Warper produces a result of true, which is really weird, and in my opinion, quite mind-bending. Hey, you can SEE the values there right in front of you and they are clearly NOT equal!
BTW, for simplicity, the Strings in my examples are exactly the same length, but you can change the length quite easily as well.
Last example concerns the HashCode of String, which is now cached for performance reasons mentioned in "Java Idiom and Performance Guide", ISBN 0130142603. (Just for the record, I was never and am still not convinced that caching the String hash code in a wrapper object is a good idea, but caching it in String itself is almost acceptable, considering String literals.)
public class CachingHashcode {
  public static void main(String[] args) {
    java.util.Map map = new java.util.HashMap();
    map.put("hi there", "You found the value");
    new Warper();
    System.out.println(map.get("hi there"));
    System.out.println(map);
  }
  private static final String greeting = "hi there";
}
The output under JDK 1.3 is:
You found the value
{cheers !=You found the value}
Under JDK 1.2 it is
null
{cheers !=You found the value}
This is because in the JDK 1.3 SUN is caching the hash code so if it once calculated, it doesn't get recalculated, so if the value field changes, the hashcode stays the same.
Imagine trying to debug this program where SOMEWHERE, one of your hackers has done a "workaround" by modifying a String literal. The thought scares me.
[Heinz: Author's note: the comment below on using "final" to solve this problem is not correct. Firstly, you cannot make arrays immutable, which is a design flaw in Java, so you could still change the content of the array even if the handle were final. Secondly, in JDK 1.5, you can set final fields using reflection. See Java 5 - "final" is not final anymore and for a similar contortion with autoboxing see Mangling Integers.]
There is of course a small keyword that would have stopped this problem, namely "final". I got into the habit a few months ago to make all my data members final where possible, and it has paid off more than once. Surprisingly, the char array in String is not final.
Consider the following example code:
public class Bla {
  private char[] c1 = "hello".toCharArray();
  private final char[] c2 = "bye".toCharArray();
  public String toString() {
    return c1 + ", " + c2;
  }
}

import java.lang.reflect.*;

public class BlaTest {
  private static Field c1;
  private static Field c2;
  static {
    try {
      c1 = Bla.class.getDeclaredField("c1");
      c1.setAccessible(true);
      c2 = Bla.class.getDeclaredField("c2");
      c2.setAccessible(true);
    } catch(NoSuchFieldException ex) { }
  }
  public static void main(String[] args) {
    Bla bla = new Bla();
    try {
      c1.set(bla, "mutatedc1".toCharArray());
      c2.set(bla, "mutatedc2".toCharArray());
    } catch(IllegalAccessException ex) {
      ex.printStackTrace();
    }
    System.out.println(bla);
  }
}
When I run my program, I can quite happily change c1, but when I try to change c2 I get an exception. String has no reason for value to be non-final, so it should be final. If you have contacts at SUN, please forward them this newsletter and ask them to make value final. It might stop some nasty Java viruses from completely messing up the JVM.

Sunday, 13 June 2010

Make a payment towards your HSBC Credit card

Well lot of people face the problem in paying ther credit card bill specially HSBC users.. .. So here is the way to help you out

To make a payment towards your HSBC Credit card, follow the 3 simple steps below:
Arrow Visit http://billdesk.com/hsbccard on you Internet browser

Arrow Follow instructions on the site to login to your non-HSBC bank account and transfer funds to your HSBC Credit card

Arrow Note down your transaction reference number





Job done :)

Thursday, 22 April 2010

Nice Quotes by great Sunny Rijhwani

I have written these quotes .. when I was not in good mood(very upset)....so here it goes
koi agar has raha hai isse pad ke to has lo.... mai bhi abhi has hi raha hu.....  ;)

"Somethings in lyf can be best rememberd as forgotten !!!!!"
"Behind every sweet memory ther is a pain !!!!!"
"Some win some loose {loser gains more I have heard that Its time for practical....}"

Try to understand this one  .. It has real deep meaning :)

"From ok to one line from one line to paragragh life goes on :) "




I have one more paragraph  which I wrote some days back:
The only difference between ---- and  ---- (code words) is the --- gives something without telling anything and expecting anything  and later one gives something and expect more than something. Although I never wanted to come in this hoshposh I just came in, It was really good in the starting, In fact it is really good now also But (see but has come) now things dont look  as sweet as it was earlier.Might be because there is no future of mine myt be attitud is not caring at all . I always believed that you be what you are.Say what u want to say and all ..Seems like its not anymore. Lyf has changed a lot . And I thnk the big change is about to come ..


-- Well it seems to u tht  i have wrtn bakwaas bt... ther was a tym infact is a tym when these thngs really matters..Although tht thing is no more with me..
Ek mast quote yaad aaraha hai. which is not mine but really gud..

The funny thing about life is that you realize the value of something ONLY when it begins to leave you."
But we usually (or always??) realize too late---AFTER it has LEFT!

Beautiful days

Well this poem is written by my very close frnd Uday shankar..
I liked this poem so publishing it here..
very nice poem (close to my heart)
uday named it as beautiful day  but I call it as Beautiful memories !
We had our first glance,
that was the start of our romance.
Then we had a small talk
while we had a pleasant walk.

We had some fortunate encounters
and we became regular chatters.
We always enjoyed each others company
so we started meeting few times ... then many.

Love was in the air,
each other was all, we care.
One day those feelings were expressed.
From that moment life get blessed.

We had our first fight,
but we can't live without others sight.
so we make up our mind,
to never leave each other behind.

Don't know what had gone wrong
I'm feeling dreadful for so long
The life has parted our ways
But those were my most beautiful days.


copyright@Udayshankardas

Thursday, 1 April 2010

Poem which is not unique :)

Pen stops Writing, Rain Stops falling,
Teacher stops scolding ,
Why not lovers stop chatting ?

Baby starts walking,
Dog starts barking,
Company starts firing,
Why not looser starts wining ?