File: UsingKnownHosts.java

package info (click to toggle)
ganymed-ssh2 250-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, buster, sid, trixie
  • size: 1,036 kB
  • sloc: java: 12,959; makefile: 23; xml: 9
file content (80 lines) | stat: -rw-r--r-- 1,717 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.KnownHosts;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

public class UsingKnownHosts
{
	static KnownHosts database = new KnownHosts();

	public static void main(String[] args) throws IOException
	{
		String hostname = "somehost";
		String username = "joe";
		String password = "joespass";

		File knownHosts = new File("~/.ssh/known_hosts");

		try
		{
			/* Load known_hosts file into in-memory database */

			if (knownHosts.exists())
				database.addHostkeys(knownHosts);

			/* Create a connection instance */

			Connection conn = new Connection(hostname);

			/* Now connect and use the SimpleVerifier */

			conn.connect(new SimpleVerifier(database));

			/* Authenticate */

			boolean isAuthenticated = conn.authenticateWithPassword(username, password);

			if (isAuthenticated == false)
				throw new IOException("Authentication failed.");

			/* Create a session */

			Session sess = conn.openSession();

			sess.execCommand("uname -a && date && uptime && who");

			InputStream stdout = new StreamGobbler(sess.getStdout());
			BufferedReader br = new BufferedReader(new InputStreamReader(stdout));

			System.out.println("Here is some information about the remote host:");

			while (true)
			{
				String line = br.readLine();
				if (line == null)
					break;
				System.out.println(line);
			}

			/* Close this session */

			sess.close();

			/* Close the connection */

			conn.close();

		}
		catch (IOException e)
		{
			e.printStackTrace(System.err);
			System.exit(2);
		}
	}
}