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.KnownHosts; 9 import ch.ethz.ssh2.Session; 10 import ch.ethz.ssh2.StreamGobbler; 11 12 public class UsingKnownHosts 13 { 14 static KnownHosts database = new KnownHosts(); 15 16 public static void main(String [] args) throws IOException 17 { 18 String hostname = "somehost"; 19 String username = "joe"; 20 String password = "joespass"; 21 22 File knownHosts = new File ("~/.ssh/known_hosts"); 23 24 try 25 { 26 27 28 if (knownHosts.exists()) 29 database.addHostkeys(knownHosts); 30 31 32 33 Connection conn = new Connection(hostname); 34 35 36 37 conn.connect(new SimpleVerifier(database)); 38 39 40 41 boolean isAuthenticated = conn.authenticateWithPassword(username, password); 42 43 if (isAuthenticated == false) 44 throw new IOException ("Authentication failed."); 45 46 47 48 Session sess = conn.openSession(); 49 50 sess.execCommand("uname -a && date && uptime && who"); 51 52 InputStream stdout = new StreamGobbler(sess.getStdout()); 53 BufferedReader br = new BufferedReader (new InputStreamReader (stdout)); 54 55 System.out.println("Here is some information about the remote host:"); 56 57 while (true) 58 { 59 String line = br.readLine(); 60 if (line == null) 61 break; 62 System.out.println(line); 63 } 64 65 66 67 sess.close(); 68 69 70 71 conn.close(); 72 73 } 74 catch (IOException e) 75 { 76 e.printStackTrace(System.err); 77 System.exit(2); 78 } 79 } 80 } 81 | Popular Tags |