1 /* 2 * Copyright (c) 2006-2011 Christian Plattner. All rights reserved. 3 * Please refer to the LICENSE.txt for licensing details. 4 */ 5 import java.io.BufferedReader; 6 import java.io.File; 7 import java.io.IOException; 8 import java.io.InputStream; 9 import java.io.InputStreamReader; 10 11 import ch.ethz.ssh2.Connection; 12 import ch.ethz.ssh2.Session; 13 import ch.ethz.ssh2.StreamGobbler; 14 15 public class PublicKeyAuthentication 16 { main(String[] args)17 public static void main(String[] args) 18 { 19 String hostname = "127.0.0.1"; 20 String username = "joe"; 21 22 File keyfile = new File("~/.ssh/id_rsa"); // or "~/.ssh/id_dsa" 23 String keyfilePass = "joespass"; // will be ignored if not needed 24 25 try 26 { 27 /* Create a connection instance */ 28 29 Connection conn = new Connection(hostname); 30 31 /* Now connect */ 32 33 conn.connect(); 34 35 /* Authenticate */ 36 37 boolean isAuthenticated = conn.authenticateWithPublicKey(username, keyfile, keyfilePass); 38 39 if (isAuthenticated == false) 40 throw new IOException("Authentication failed."); 41 42 /* Create a session */ 43 44 Session sess = conn.openSession(); 45 46 sess.execCommand("uname -a && date && uptime && who"); 47 48 InputStream stdout = new StreamGobbler(sess.getStdout()); 49 50 BufferedReader br = new BufferedReader(new InputStreamReader(stdout)); 51 52 System.out.println("Here is some information about the remote host:"); 53 54 while (true) 55 { 56 String line = br.readLine(); 57 if (line == null) 58 break; 59 System.out.println(line); 60 } 61 62 /* Close this session */ 63 64 sess.close(); 65 66 /* Close the connection */ 67 68 conn.close(); 69 70 } 71 catch (IOException e) 72 { 73 e.printStackTrace(System.err); 74 System.exit(2); 75 } 76 } 77 } 78