3 import java
.io
.IOException
;
4 import java
.nio
.file
.Path
;
5 import java
.nio
.file
.Paths
;
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
;
13 /** A simple SSH server with some defaults. Supports SCP. */
14 public class SimpleSshServer
{
16 private Path hostKeyPath
;
18 private SshServer sshd
= null;
20 public SimpleSshServer(Integer port
, Path hostKeyPath
) {
22 this.hostKeyPath
= hostKeyPath
;
27 sshd
= SshServer
.setUpDefaultServer();
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",
34 String
[] shellCommand
= OS
.LOCAL
.getDefaultShellCommand();
35 sshd
.setShellFactory(new ProcessShellFactory(shellCommand
));
36 sshd
.setCommandFactory(new ScpCommandFactory());
38 } catch (Exception e
) {
39 throw new RuntimeException("Cannot start SSH server on port " + port
, e
);
43 public void destroy() {
46 } catch (IOException e
) {
47 throw new RuntimeException("Cannot stop SSH server on port " + port
, e
);
51 public Integer
getPort() {
55 public void setPort(Integer port
) {
59 public Path
getHostKeyPath() {
63 public void setHostKeyPath(Path hostKeyPath
) {
64 this.hostKeyPath
= hostKeyPath
;
67 public static void main(String
[] args
) {
69 Path hostKeyPath
= Paths
.get("hostkey.ser");
72 port
= Integer
.parseInt(args
[0]);
74 hostKeyPath
= Paths
.get(args
[1]);
75 } catch (Exception e1
) {
79 SimpleSshServer sshServer
= new SimpleSshServer(port
, hostKeyPath
);
81 Runtime
.getRuntime().addShutdownHook(new Thread("Shutdown SSH server") {
89 synchronized (sshServer
) {
92 } catch (InterruptedException e
) {
98 public static void printUsage() {
99 System
.out
.println("java " + SimpleSshServer
.class.getName() + " [port] [server key path]");