9/01/2015

Execute putty (Plink) commands (On remote Linux machine) from java



Execute putty commands (On remote Linux machine) from java


1.       Before executing this program we need to download putty and Plink from below link. Put the downloaded files in one folder. (ex: C:\putty). After download istall or run once putty.exe and plink.exe


2.       We need to set this folder to class path  or In java program set the right folder path in below line. And execute the program.



Below is the example java program. you can test your commend replacing the correct host,username and password. and line # 26 with right command.

Note: Make sure that your commend must end with \n. 





 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import java.io.InputStream;
import java.io.OutputStream;

public class PuttyTest {
 private static String host = "***";
 private static String userName = "***";
 private static String password = "****";

 public static void main(String args[]) throws Exception
 {
  PuttyTest test=new PuttyTest();
  System.out.println(test.getLimServerStatus());
 }
 
 public String getLimServerStatus() throws Exception {

  try {
      String command = "c:/putty/plink -v "+host+" -l "+userName+" -pw "+password;
      Runtime r = Runtime.getRuntime ();
      Process p = r.exec (command);
      Thread.sleep (1000);
      InputStream std = p.getInputStream ();
      OutputStream out = p.getOutputStream ();
      //InputStream err = p.getErrorStream ();

      out.write ("tail -n 1000 config/load_updates.hst | grep \"Error\" | wc -l\n".getBytes ());
      out.flush ();

      Thread.sleep (3000);

      int value = 0;
      String otherString=null;
      if (std.available () > 0) {
          value = std.read();
          otherString=String.valueOf((char) value);
          while (std.available() > 0) {
              value = std.read();
              otherString+=String.valueOf((char) value);
          }
      }
     
      int count=0;
      String[] lines = otherString.split("\r\n|\r|\n");
      for (String string : lines) {
    System.out.println(string+" :"+count++);
   }
      p.destroy ();
      return lines[lines.length-2]; // needed output is in third line.
      
 }catch(Exception e)
 {
  e.printStackTrace();
 }
  return null;
 }
}

2 comments: