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