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
;
13 /** A simple SSH server with some defaults. Supports SCP. */
14 @SuppressWarnings("restriction")
15 public class BasicSshServer
{
17 private Path hostKeyPath
;
19 private SshServer sshd
= null;
21 public BasicSshServer(Integer port
, Path hostKeyPath
) {
23 this.hostKeyPath
= hostKeyPath
;
28 sshd
= SshServer
.setUpDefaultServer();
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",
35 String
[] shellCommand
= OS
.LOCAL
.getDefaultShellCommand();
36 sshd
.setShellFactory(new ProcessShellFactory(shellCommand
));
37 sshd
.setCommandFactory(new ScpCommandFactory());
39 } catch (Exception e
) {
40 throw new RuntimeException("Cannot start SSH server on port " + port
, e
);
44 public void destroy() {
47 } catch (IOException e
) {
48 throw new RuntimeException("Cannot stop SSH server on port " + port
, e
);
52 public Integer
getPort() {
56 public void setPort(Integer port
) {
60 public Path
getHostKeyPath() {
64 public void setHostKeyPath(Path hostKeyPath
) {
65 this.hostKeyPath
= hostKeyPath
;
68 public static void main(String
[] args
) {
70 Path hostKeyPath
= Paths
.get("hostkey.ser");
73 port
= Integer
.parseInt(args
[0]);
75 hostKeyPath
= Paths
.get(args
[1]);
76 } catch (Exception e1
) {
80 BasicSshServer sshServer
= new BasicSshServer(port
, hostKeyPath
);
82 Runtime
.getRuntime().addShutdownHook(new Thread("Shutdown SSH server") {
90 synchronized (sshServer
) {
93 } catch (InterruptedException e
) {
99 public static void printUsage() {
100 System
.out
.println("java " + BasicSshServer
.class.getName() + " [port] [server key path]");