KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > Basic


1 import java.io.BufferedReader JavaDoc;
2 import java.io.IOException JavaDoc;
3 import java.io.InputStream JavaDoc;
4 import java.io.InputStreamReader JavaDoc;
5
6 import ch.ethz.ssh2.Connection;
7 import ch.ethz.ssh2.Session;
8 import ch.ethz.ssh2.StreamGobbler;
9
10 public class Basic
11 {
12     public static void main(String JavaDoc[] args)
13     {
14         String JavaDoc hostname = "127.0.0.1";
15         String JavaDoc username = "joe";
16         String JavaDoc password = "joespass";
17
18         try
19         {
20             /* Create a connection instance */
21
22             Connection conn = new Connection(hostname);
23
24             /* Now connect */
25
26             conn.connect();
27
28             /* Authenticate.
29              * If you get an IOException saying something like
30              * "Authentication method password not supported by the server at this stage."
31              * then please check the FAQ.
32              */

33
34             boolean isAuthenticated = conn.authenticateWithPassword(username, password);
35
36             if (isAuthenticated == false)
37                 throw new IOException JavaDoc("Authentication failed.");
38
39             /* Create a session */
40
41             Session sess = conn.openSession();
42
43             sess.execCommand("uname -a && date && uptime && who");
44
45             System.out.println("Here is some information about the remote host:");
46
47             /*
48              * This basic example does not handle stderr, which is sometimes dangerous
49              * (please read the FAQ).
50              */

51
52             InputStream JavaDoc stdout = new StreamGobbler(sess.getStdout());
53
54             BufferedReader JavaDoc br = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(stdout));
55
56             while (true)
57             {
58                 String JavaDoc line = br.readLine();
59                 if (line == null)
60                     break;
61                 System.out.println(line);
62             }
63
64             /* Show exit status, if available (otherwise "null") */
65
66             System.out.println("ExitCode: " + sess.getExitStatus());
67
68             /* Close this session */
69
70             sess.close();
71
72             /* Close the connection */
73
74             conn.close();
75
76         }
77         catch (IOException JavaDoc e)
78         {
79             e.printStackTrace(System.err);
80             System.exit(2);
81         }
82     }
83 }
84
Popular Tags