]> git.argeo.org Git - lgpl/argeo-commons.git/blob - org.argeo.core/src/org/argeo/ssh/SimpleSshServer.java
Make data admin log-in more robust and easier to use.
[lgpl/argeo-commons.git] / org.argeo.core / src / org / argeo / ssh / SimpleSshServer.java
1 package org.argeo.ssh;
2
3 import java.io.IOException;
4 import java.nio.file.Path;
5 import java.nio.file.Paths;
6
7 import org.apache.sshd.server.SshServer;
8 import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider;
9 import org.apache.sshd.server.scp.ScpCommandFactory;
10 import org.apache.sshd.server.shell.ProcessShellFactory;
11 import org.argeo.util.os.OS;
12
13 /** A simple SSH server with some defaults. Supports SCP. */
14 public class SimpleSshServer {
15 private Integer port;
16 private Path hostKeyPath;
17
18 private SshServer sshd = null;
19
20 public SimpleSshServer(Integer port, Path hostKeyPath) {
21 this.port = port;
22 this.hostKeyPath = hostKeyPath;
23 }
24
25 public void init() {
26 try {
27 sshd = SshServer.setUpDefaultServer();
28 sshd.setPort(port);
29 if (hostKeyPath == null)
30 throw new IllegalStateException("An SSH server key must be set");
31 sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(hostKeyPath));
32 // sshd.setShellFactory(new ProcessShellFactory(new String[] { "/bin/sh", "-i",
33 // "-l" }));
34 String[] shellCommand = OS.LOCAL.getDefaultShellCommand();
35 sshd.setShellFactory(new ProcessShellFactory(shellCommand));
36 sshd.setCommandFactory(new ScpCommandFactory());
37 sshd.start();
38 } catch (Exception e) {
39 throw new RuntimeException("Cannot start SSH server on port " + port, e);
40 }
41 }
42
43 public void destroy() {
44 try {
45 sshd.stop();
46 } catch (IOException e) {
47 throw new RuntimeException("Cannot stop SSH server on port " + port, e);
48 }
49 }
50
51 public Integer getPort() {
52 return port;
53 }
54
55 public void setPort(Integer port) {
56 this.port = port;
57 }
58
59 public Path getHostKeyPath() {
60 return hostKeyPath;
61 }
62
63 public void setHostKeyPath(Path hostKeyPath) {
64 this.hostKeyPath = hostKeyPath;
65 }
66
67 public static void main(String[] args) {
68 int port = 2222;
69 Path hostKeyPath = Paths.get("hostkey.ser");
70 try {
71 if (args.length > 0)
72 port = Integer.parseInt(args[0]);
73 if (args.length > 1)
74 hostKeyPath = Paths.get(args[1]);
75 } catch (Exception e1) {
76 printUsage();
77 }
78
79 SimpleSshServer sshServer = new SimpleSshServer(port, hostKeyPath);
80 sshServer.init();
81 Runtime.getRuntime().addShutdownHook(new Thread("Shutdown SSH server") {
82
83 @Override
84 public void run() {
85 sshServer.destroy();
86 }
87 });
88 try {
89 synchronized (sshServer) {
90 sshServer.wait();
91 }
92 } catch (InterruptedException e) {
93 sshServer.destroy();
94 }
95
96 }
97
98 public static void printUsage() {
99 System.out.println("java " + SimpleSshServer.class.getName() + " [port] [server key path]");
100 }
101
102 }