skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Thursday, October 4, 2012

Remote Unix server access using Java Secure Channel

Posted by Admin at 10:21 PM – 0 comments
 

Using the concept of Java secure channel, I had created a ssh tunnel, to logon to any remote unix system securely. I will pass the commands to be executed using the Input Stream. The output of the commands will be passed to the console using a Output stream. The output of command execution can also be redirected to a file. For using this utiliy, you will need to have the latest jsch_.jar in your library and include "com.jcraft.jsch.*" in your source code. To know more about Java Secure Channel, please visit, http://www.jcraft.com/jsch/


public class precheck {
 public static void main(String args[]) {
  String user = "USER_ID";
  String host = "HOST_NAME";
  String cmd = "pwd;id;cd /opt/tib;pwd; df -k .;ls -ld .";
  JSch jsch = new JSch();
  try {
   Session session = jsch.getSession(user, host, 22);
   UserInfo usrInfo = new MyUserInfo();
   session.setUserInfo(usrInfo);
   session.connect();
   Channel channel = session.openChannel("exec");
   ((ChannelExec) channel).setCommand(cmd);
   channel.setXForwarding(true);
   ((ChannelExec) channel).setOutputStream(System.out);
   ((ChannelExec) channel).setErrStream(System.err);

   InputStream in = channel.getInputStream();
   channel.connect();
   channel.setInputStream(System.in);
   // System.err.println(System.err);
   byte[] tmp = new byte[1024];
   while (true) {
    while (in.available() > 0) {
     int i = in.read(tmp, 0, 1024);
     if (i < 0)
      break;
     System.out.print(new String(tmp, 0, i));

    }
    if (channel.isClosed()) {
     in.close();
     break;
    }
    try {
     Thread.sleep(1000);
    } catch (Exception ee) {
    }
   }
   channel.disconnect();
   session.disconnect();
  } catch (Exception e) {
   e.printStackTrace();
   System.out.println("Exception" + e);
  }
 }

 public static class MyUserInfo implements UserInfo {
  public String getPassword() {
   return "PASSWORD";
  }

  public String getPassphrase() {
   return "";
  }

  public boolean promptPassword(String arg0) {
   return true;
  }

  public boolean promptPassphrase(String arg0) {
   return true;
  }

  public boolean promptYesNo(String arg0) {
   return true;
  }

  public void showMessage(String arg0) {
  }
 }
}


Leave a Reply

Newer Post Older Post
Subscribe to: Post Comments ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger