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