1 import java.io.BufferedReader ; 2 import java.io.File ; 3 import java.io.IOException ; 4 import java.io.InputStream ; 5 import java.io.InputStreamReader ; 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 [] args) 14 { 15 String hostname = "127.0.0.1"; 16 String username = "joe"; 17 18 File keyfile = new File ("~/.ssh/id_rsa"); String keyfilePass = "joespass"; 21 try 22 { 23 24 25 Connection conn = new Connection(hostname); 26 27 28 29 conn.connect(); 30 31 32 33 boolean isAuthenticated = conn.authenticateWithPublicKey(username, keyfile, keyfilePass); 34 35 if (isAuthenticated == false) 36 throw new IOException ("Authentication failed."); 37 38 39 40 Session sess = conn.openSession(); 41 42 sess.execCommand("uname -a && date && uptime && who"); 43 44 InputStream stdout = new StreamGobbler(sess.getStdout()); 45 46 BufferedReader br = new BufferedReader (new InputStreamReader (stdout)); 47 48 System.out.println("Here is some information about the remote host:"); 49 50 while (true) 51 { 52 String line = br.readLine(); 53 if (line == null) 54 break; 55 System.out.println(line); 56 } 57 58 59 60 sess.close(); 61 62 63 64 conn.close(); 65 66 } 67 catch (IOException e) 68 { 69 e.printStackTrace(System.err); 70 System.exit(2); 71 } 72 } 73 } 74 | Popular Tags |