KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > PublicKeyAuthentication


1 import java.io.BufferedReader JavaDoc;
2 import java.io.File JavaDoc;
3 import java.io.IOException JavaDoc;
4 import java.io.InputStream JavaDoc;
5 import java.io.InputStreamReader JavaDoc;
6
7 import ch.ethz.ssh2.Connection;
8 import ch.ethz.ssh2.Session;
9 import ch.ethz.ssh2.StreamGobbler;
10
11 public class PublicKeyAuthentication
12 {
13     public static void main(String JavaDoc[] args)
14     {
15         String JavaDoc hostname = "127.0.0.1";
16         String JavaDoc username = "joe";
17
18         File JavaDoc keyfile = new File JavaDoc("~/.ssh/id_rsa"); // or "~/.ssh/id_dsa"
19
String JavaDoc keyfilePass = "joespass"; // will be ignored if not needed
20

21         try
22         {
23             /* Create a connection instance */
24
25             Connection conn = new Connection(hostname);
26
27             /* Now connect */
28
29             conn.connect();
30
31             /* Authenticate */
32
33             boolean isAuthenticated = conn.authenticateWithPublicKey(username, keyfile, keyfilePass);
34
35             if (isAuthenticated == false)
36                 throw new IOException JavaDoc("Authentication failed.");
37
38             /* Create a session */
39
40             Session sess = conn.openSession();
41
42             sess.execCommand("uname -a && date && uptime && who");
43
44             InputStream JavaDoc stdout = new StreamGobbler(sess.getStdout());
45
46             BufferedReader JavaDoc br = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(stdout));
47
48             System.out.println("Here is some information about the remote host:");
49
50             while (true)
51             {
52                 String JavaDoc line = br.readLine();
53                 if (line == null)
54                     break;
55                 System.out.println(line);
56             }
57
58             /* Close this session */
59             
60             sess.close();
61
62             /* Close the connection */
63
64             conn.close();
65
66         }
67         catch (IOException JavaDoc e)
68         {
69             e.printStackTrace(System.err);
70             System.exit(2);
71         }
72     }
73 }
74
Popular Tags