Java Code Examples for org.apache.sshd.server.SshServer

The following examples show how to use org.apache.sshd.server.SshServer. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: termd   Source File: NettySshTtyBootstrap.java    License: Apache License 2.0 6 votes vote down vote up
public void start(final Consumer<TtyConnection> factory, Consumer<Throwable> doneHandler) {
  server = SshServer.setUpDefaultServer();
  server.setIoServiceFactoryFactory(new NettyIoServiceFactoryFactory(childGroup));
  server.setPort(port);
  server.setHost(host);
  server.setKeyPairProvider(keyPairProvider);
  server.setPasswordAuthenticator(passwordAuthenticator);
  server.setShellFactory(new Factory<Command>() {
    @Override
    public Command create() {
      return new TtyCommand(charset, factory);
    }
  });
  try {
    server.start();
  } catch (Exception e) {
    doneHandler.accept(e);
    return;
  }
  doneHandler.accept(null);
}
 
Example 2
Source Project: termd   Source File: AsyncAuthTestBase.java    License: Apache License 2.0 6 votes vote down vote up
public void startServer(Integer timeout) throws Exception {
  if (server != null) {
    throw failure("Server already started");
  }
  server = SshServer.setUpDefaultServer();
  if (timeout != null) {
    server.getProperties().put(FactoryManager.AUTH_TIMEOUT, timeout.toString());
  }
  server.setPort(5000);
  server.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(new File("hostkey.ser").toPath()));
  server.setPasswordAuthenticator(new PasswordAuthenticator() {
    @Override
    public boolean authenticate(String username, String password, ServerSession session) throws PasswordChangeRequiredException {
      return authenticator.authenticate(username, password, session);
    }
  });
  server.setShellFactory(new EchoShellFactory());
  server.setServiceFactories(Arrays.asList(ServerConnectionServiceFactory.INSTANCE, AsyncUserAuthServiceFactory.INSTANCE));
  server.start();
}
 
Example 3
/**
 * Construct ssh server thanks to ssh shell properties
 *
 * @return ssh server
 */
@Bean
public SshServer sshServer() {
    SshServer server = SshServer.setUpDefaultServer();
    server.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(properties.getHostKeyFile().toPath()));
    server.setHost(properties.getHost());
    server.setPasswordAuthenticator(passwordAuthenticator);
    server.setPublickeyAuthenticator(RejectAllPublickeyAuthenticator.INSTANCE);
    if (properties.getAuthorizedPublicKeysFile() != null) {
        if (properties.getAuthorizedPublicKeysFile().exists() && properties.getAuthorizedPublicKeysFile().canRead()) {
            server.setPublickeyAuthenticator(new SshShellPublicKeyAuthenticationProvider(properties.getAuthorizedPublicKeysFile()));
        } else {
            LOGGER.warn("Could not read authorized public keys file [{}], public key authentication is disabled.",
                    properties.getAuthorizedPublicKeysFile().getAbsolutePath());
        }
    }
    server.setPort(properties.getPort());
    server.setShellFactory(channelSession -> shellCommandFactory);
    server.setCommandFactory((channelSession, s) -> shellCommandFactory);
    return server;
}
 
Example 4
Source Project: onedev   Source File: SshServerLauncher.java    License: MIT License 6 votes vote down vote up
@Listen
  public void on(SystemStarted event) {
      server = SshServer.setUpDefaultServer();

      server.setPort(serverConfig.getSshPort());
      server.setKeyPairProvider(keyPairProvider);
      server.setShellFactory(new DisableShellAccess());
      
      server.setPublickeyAuthenticator(new CachingPublicKeyAuthenticator(authenticator));
      server.setKeyboardInteractiveAuthenticator(null);
      
      server.setCommandFactory(command -> {
      	for (SshCommandCreator creator: commandCreators) {
      		Command sshCommand = creator.createCommand(command);
      		if (sshCommand != null)
      			return sshCommand;
      	}
          return new UnknownCommand(command);
      });

      try {
	server.start();
} catch (IOException e) {
	throw new RuntimeException(e);
}
  }
 
Example 5
Source Project: fake-sftp-server-rule   Source File: FakeSftpServerRule.java    License: MIT License 6 votes vote down vote up
private SshServer startServer(
    FileSystem fileSystem
) throws IOException {
    SshServer server = SshServer.setUpDefaultServer();
    server.setPort(port);
    server.setKeyPairProvider(new SimpleGeneratorHostKeyProvider());
    server.setPasswordAuthenticator(this::authenticate);
    server.setSubsystemFactories(singletonList(new SftpSubsystemFactory()));
    /* When a channel is closed SshServer calls close() on the file system.
     * In order to use the file system for multiple channels/sessions we
     * have to use a file system wrapper whose close() does nothing.
     */
    server.setFileSystemFactory(session -> new DoNotClose(fileSystem));
    server.start();
    this.server = server;
    return server;
}
 
Example 6
Source Project: ssh-proxy   Source File: SshProxyTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(timeout = TEST_TIMEOUT_MILLIS)
public void testSingleHop() throws Exception {
	SshServer sshServer = setUpSshServer();
	int sshServerPort = sshServer.getPort();

	String hostConfigName = "localhost-" + sshServerPort;
	appendToSshFile(CONFIG_FILENAME, "Host " + hostConfigName + "\n\tHostName localhost\n\tPort " + sshServerPort + "\n\n");

	try (DummyServerSocketThread dummyServerSocketThread = new DummyServerSocketThread(TRANSFER_CHARSET, TEST_TEXT);
		SshProxy sshProxy = new SshProxy()) {
		int port = sshProxy.connect(hostConfigName, "localhost", dummyServerSocketThread.getPort());

		final String receivedText;
		try (Socket s = new Socket(SshProxy.LOCALHOST, port);
			 InputStream is = s.getInputStream()) {
			log.info("connected to port: {}", port);
			receivedText = readLine(is);
		}
		assertEquals(TEST_TEXT, receivedText);
	} finally {
		tryStop(sshServer);
	}
}
 
Example 7
Source Project: ssh-proxy   Source File: SshProxyTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(timeout = TEST_TIMEOUT_MILLIS)
public void testSingleHop_EcDsaServer() throws Exception {
	SshServer sshServer = setUpSshServer(KeyUtils.EC_ALGORITHM);
	int sshServerPort = sshServer.getPort();

	String hostConfigName = "localhost-" + sshServerPort;
	appendToSshFile(CONFIG_FILENAME, "Host " + hostConfigName + "\n\tHostName localhost\n\tPort " + sshServerPort + "\n\n");

	try (DummyServerSocketThread dummyServerSocketThread = new DummyServerSocketThread(TRANSFER_CHARSET, TEST_TEXT);
		SshProxy sshProxy = new SshProxy()) {
		int port = sshProxy.connect(hostConfigName, "localhost", dummyServerSocketThread.getPort());

		final String receivedText;
		try (Socket s = new Socket(SshProxy.LOCALHOST, port);
			 InputStream is = s.getInputStream()) {
			log.info("connected to port: {}", port);
			receivedText = readLine(is);
		}
		assertEquals(TEST_TEXT, receivedText);
	} finally {
		tryStop(sshServer);
	}
}
 
Example 8
Source Project: ssh-proxy   Source File: SshProxyTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(timeout = TEST_TIMEOUT_MILLIS)
public void testSingleHopWithLocalPort() throws Exception {
	SshServer sshServer = setUpSshServer();
	int sshServerPort = sshServer.getPort();

	String hostConfigName = "localhost-" + sshServerPort;
	appendToSshFile(CONFIG_FILENAME, "Host " + hostConfigName + "\n\tHostName localhost\n\tPort " + sshServerPort + "\n\n");

	try (DummyServerSocketThread dummyServerSocketThread = new DummyServerSocketThread(TRANSFER_CHARSET, TEST_TEXT);
		SshProxy sshProxy = new SshProxy()) {
		int port = sshProxy.connect(hostConfigName, "localhost", dummyServerSocketThread.getPort(), 2345);

		final String receivedText;
		try (Socket s = new Socket(SshProxy.LOCALHOST, port);
			 InputStream is = s.getInputStream()) {
			log.info("connected to port: {}", port);
			receivedText = readLine(is);
		}
		assertEquals(TEST_TEXT, receivedText);
	} finally {
		tryStop(sshServer);
	}
}
 
Example 9
Source Project: ssh-proxy   Source File: SshProxyTest.java    License: Apache License 2.0 6 votes vote down vote up
private void doTestTwoHops(String proxyConfiguration) throws Exception {
	SshServer firstSshServer = setUpSshServer();
	int firstServerPort = firstSshServer.getPort();

	SshServer secondSshServer = setUpSshServer();
	int secondServerPort = secondSshServer.getPort();

	appendToSshFile(CONFIG_FILENAME, "Host firsthop\n\tHostName localhost\n\tPort " + firstServerPort + "\n\n");
	appendToSshFile(CONFIG_FILENAME, "Host secondhop\n\tHostName localhost\n\tPort " + secondServerPort + "\n\t" + proxyConfiguration + "\n\n");

	try (DummyServerSocketThread dummyServerSocketThread = new DummyServerSocketThread(TRANSFER_CHARSET, TEST_TEXT);
		 SshProxy sshProxy = new SshProxy()) {
		int port = sshProxy.connect("secondhop", "localhost", dummyServerSocketThread.getPort());

		final String receivedText;
		try (Socket s = new Socket(SshProxy.LOCALHOST, port);
			 InputStream is = s.getInputStream()) {
			log.info("connected to port: {}", port);
			receivedText = readLine(is);
		}
		assertEquals(TEST_TEXT, receivedText);
	} finally {
		tryStop(firstSshServer);
		tryStop(secondSshServer);
	}
}
 
Example 10
Source Project: ssh-proxy   Source File: SshProxyTest.java    License: Apache License 2.0 6 votes vote down vote up
private SshServer setUpSshServer(String algorithm) throws IOException {
	SshServer sshServer = SshServer.setUpDefaultServer();
	sshServer.setPort(0);
	AbstractGeneratorHostKeyProvider hostKeyProvider = SecurityUtils.createGeneratorHostKeyProvider(getServerKeyFile(algorithm));
	hostKeyProvider.setAlgorithm(algorithm);
	if (algorithm.equals(KeyUtils.EC_ALGORITHM)) {
		hostKeyProvider.setKeySize(256);
	}
	sshServer.setKeyPairProvider(hostKeyProvider);

	sshServer.setPublickeyAuthenticator(AcceptAllPublickeyAuthenticator.INSTANCE);
	sshServer.setForwardingFilter(AcceptAllForwardingFilter.INSTANCE);

	writeFingerprintToKnownHosts(algorithm);

	sshServer.start();

	int sshServerPort = sshServer.getPort();
	assertTrue(sshServerPort > 0);

	return sshServer;
}
 
Example 11
Source Project: aesh-readline   Source File: NettySshTtyBootstrap.java    License: Apache License 2.0 6 votes vote down vote up
public void start(Consumer<Connection> factory, Consumer<Throwable> doneHandler) {
    server = SshServer.setUpDefaultServer();
    server.setIoServiceFactoryFactory(new NettyIoServiceFactoryFactory(childGroup));
    server.setPort(port);
    server.setHost(host);
    server.setKeyPairProvider(keyPairProvider);
    server.setPasswordAuthenticator(passwordAuthenticator);
    if (publicKeyAuthenticator != null) {
        server.setPublickeyAuthenticator(publicKeyAuthenticator);
    }
    server.setShellFactory(() -> new TtyCommand(charset, factory));
    try {
        server.start();
    } catch (Exception e) {
        doneHandler.accept(e);
        return;
    }
    doneHandler.accept(null);
}
 
Example 12
Source Project: vertx-shell   Source File: SSHServer.java    License: Apache License 2.0 6 votes vote down vote up
public void close(Handler<AsyncResult<Void>> completionHandler) {
  if (!status.compareAndSet(STATUS_STARTED, STATUS_STOPPING)) {
    completionHandler.handle(Future.failedFuture("Invalid state:" + status.get()));
    return;
  }
  vertx.executeBlocking(fut-> {
    try {
      SshServer server = this.nativeServer;
      this.nativeServer = null;
      server.close();
      completionHandler.handle(Future.succeededFuture());
    } catch (Exception t) {
      completionHandler.handle(Future.failedFuture(t));
    } finally {
      status.set(STATUS_STOPPED);
    }
  }, completionHandler);
}
 
Example 13
Source Project: termd   Source File: NettySshTtyBootstrap.java    License: Apache License 2.0 6 votes vote down vote up
public void start(Consumer<TtyConnection> factory, Consumer<Throwable> doneHandler) {
  server = SshServer.setUpDefaultServer();
  server.setIoServiceFactoryFactory(new NettyIoServiceFactoryFactory(childGroup));
  server.setPort(port);
  server.setHost(host);
  server.setKeyPairProvider(keyPairProvider);
  server.setPasswordAuthenticator(passwordAuthenticator);
  server.setShellFactory(() -> new TtyCommand(charset, factory));
  try {
    server.start();
  } catch (Exception e) {
    doneHandler.accept(e);
    return;
  }
  doneHandler.accept(null);
}
 
Example 14
Source Project: tomee   Source File: SSHServer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void start() throws ServiceException {
    sshServer = SshServer.setUpDefaultServer();
    sshServer.setPort(port);
    sshServer.setHost(bind);

    final String basePath = SystemInstance.get().getBase().getDirectory().getAbsolutePath();
    if (SecurityUtils.isBouncyCastleRegistered()) {
        sshServer.setKeyPairProvider(new BouncyCastleGeneratorHostKeyProvider(new File(basePath, KEY_NAME + ".pem").toPath()));
    } else {
        sshServer.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(new File(basePath, KEY_NAME + ".ser").toPath()));
    }

    final OpenEJBShellFactory sf = new OpenEJBShellFactory(bind, port);
    sshServer.setShellFactory(sf);

    final JaasPasswordAuthenticator authenticator = new OpenEJBJaasPasswordAuthenticator();
    authenticator.setDomain(domain);
    sshServer.setPasswordAuthenticator(authenticator);

    try {
        sshServer.start();
    } catch (IOException e) {
        // no-op
    }
}
 
Example 15
Source Project: micro-integrator   Source File: ESBJAVA3470.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Starts a SFTP server on port 22
 * @param carbonHome
 */
private void setupSftpServer(String carbonHome) {
    SshServer sshd = SshServer.setUpDefaultServer();
    sshd.setPort(FTP_PORT);
    //sshd.setKeyPairProvider(new FileKeyPairProvider(new
    // String[]{"/home/ravi/WORK/SUPPORT/JIRA/SKYTVNZDEV-26/SftpTest/dist/hostkey.ser"}));
    ClassLoader classLoader = getClass().getClassLoader();
    log.info("Using identity file: " + classLoader.getResource("sftp/id_rsa.pub").getFile());
    File file = new File(classLoader.getResource("sftp/id_rsa.pub").getFile());
    sshd.setKeyPairProvider(createTestHostKeyProvider(Paths.get(file.getAbsolutePath())));
    sshd.setUserAuthFactories(Arrays.asList(new UserAuthPublicKeyFactory()));
    sshd.setFileSystemFactory(new VirtualFileSystemFactory(Paths.get(carbonHome)));
    sshd.setPublickeyAuthenticator(new PublickeyAuthenticator() {
        public boolean authenticate(String username, PublicKey key, ServerSession session) {
            return "sftpuser".equals(username);
        }
    });
    sshd.setCommandFactory(new ScpCommandFactory());
    sshd.setSubsystemFactories(Arrays.asList(new SftpSubsystemFactory()));
    SftpServerRunner sftpServerRunner = new SftpServerRunner(sshd);

    try {
        sftpServerRunner.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 16
Source Project: camel-quarkus   Source File: SftpTestResource.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, String> start() {
    try {
        final int port = AvailablePortFinder.getNextAvailable();

        sftpHome = Files.createTempDirectory("sftp-");
        sshHome = sftpHome.resolve("admin/.ssh");

        Files.createDirectories(sshHome);

        byte[] knownHostsBytes = String.format(KNOWN_HOSTS, port).getBytes(StandardCharsets.UTF_8);
        Files.write(sshHome.resolve(".known_hosts"), knownHostsBytes);

        VirtualFileSystemFactory factory = new VirtualFileSystemFactory();
        factory.setUserHomeDir("admin", sftpHome.resolve("admin").toAbsolutePath());

        sshServer = SshServer.setUpDefaultServer();
        sshServer.setPort(port);
        sshServer.setKeyPairProvider(new ClassLoadableResourceKeyPairProvider("hostkey.pem"));
        sshServer.setSubsystemFactories(Collections.singletonList(new SftpSubsystemFactory()));
        sshServer.setCommandFactory(new ScpCommandFactory());
        sshServer.setPasswordAuthenticator((username, password, session) -> true);
        sshServer.setPublickeyAuthenticator((username, key, session) -> true);
        sshServer.setFileSystemFactory(factory);
        sshServer.start();

        return CollectionHelper.mapOf("camel.sftp.test-port", Integer.toString(port));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 17
Source Project: termd   Source File: Utils.java    License: Apache License 2.0 5 votes vote down vote up
public static SshServer setupTestServer(Class<?> anchor) {
    SshServer sshd = SshServer.setUpDefaultServer();
    sshd.setKeyPairProvider(createTestHostKeyProvider(anchor));
    sshd.setPasswordAuthenticator(BogusPasswordAuthenticator.INSTANCE);
    sshd.setPublickeyAuthenticator(AcceptAllPublickeyAuthenticator.INSTANCE);
    sshd.setShellFactory(EchoShellFactory.INSTANCE);
    sshd.setCommandFactory(UnknownCommandFactory.INSTANCE);
    return sshd;
}
 
Example 18
Source Project: quarkus   Source File: JSchTest.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void setupSSHDServer() throws Exception {
    sshd = SshServer.setUpDefaultServer();
    sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(Files.createTempFile("host", "key")));
    sshd.setHostBasedAuthenticator(AcceptAllHostBasedAuthenticator.INSTANCE);
    sshd.setPasswordAuthenticator(AcceptAllPasswordAuthenticator.INSTANCE);
    sshd.setPublickeyAuthenticator(AcceptAllPublickeyAuthenticator.INSTANCE);
    sshd.setCommandFactory(UnknownCommandFactory.INSTANCE);
    sshd.setHost("localhost");
    sshd.start();
}
 
Example 19
@Before
public void startSerer() throws Exception {
    server = SshServer.setUpDefaultServer();
    server.setPort(PORT_NUMBER);
    server.setPasswordAuthenticator((username, password, session) -> true);
    server.setKeyPairProvider(new SimpleGeneratorHostKeyProvider());
    server.setSubsystemFactories(Collections.singletonList(new SftpSubsystemFactory()));
    final java.nio.file.Path tempDir = Files.createTempDirectory(String.format("%s-", this.getClass().getName()));
    final java.nio.file.Path vault = tempDir.resolve("vault");
    Files.createDirectory(vault);
    passphrase = new AlphanumericRandomStringService().random();
    cryptoFileSystem = CryptoFileSystemProvider.newFileSystem(vault, CryptoFileSystemProperties.cryptoFileSystemProperties().withPassphrase(passphrase).build());
    server.setFileSystemFactory(new VirtualFileSystemFactory(cryptoFileSystem.getPathToVault().getParent().toAbsolutePath()));
    server.start();
}
 
Example 20
@Bean
SshServer sshServer() {
    Shell props = properties.getShell();
    if (Objects.isNull(props.getPassword())) {
        props.setPassword(UUID.randomUUID().toString());
        log.info("********** User password not set. Use following password to login: {} **********",
                props.getPassword());
    }
    return buildServer(props);
}
 
Example 21
private SshServer buildServer(Shell props) {
    SshServer server = SshServer.setUpDefaultServer();
    server.setHost(props.getHost());
    server.setPort(props.getPort());
    configureAuthenticationPolicies(server, props);
    configureServer(server);
    return server;
}
 
Example 22
private void configureAuthenticationPolicies(SshServer server, Shell props) {
    server.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(Paths.get(props.getHostKeyFile())));
    server.setPublickeyAuthenticator(Objects.isNull(props.getPublicKeyFile())
            ? RejectAllPublickeyAuthenticator.INSTANCE
            : new SshdAuthorizedKeysAuthenticator(Paths.get(props.getPublicKeyFile())));
    server.setPasswordAuthenticator(passwordAuthenticator(props));
}
 
Example 23
private void configureServer(SshServer server) {
    if (properties.getFiletransfer().isEnabled()) {
        configureServerForSshAndFileTransfer(server);
    } else {
        configureServerForSshOnly(server);
    }
    configureShellFactory(server);
}
 
Example 24
@PostConstruct
void startServer() throws IOException {
    SshServer server = sshServer();
    server.start();
    properties.getShell().setPort(server.getPort()); // In case server port is 0, a random port is assigned.
    log.info("SSH server started on port {}", properties.getShell().getPort());
}
 
Example 25
Source Project: product-ei   Source File: ESBJAVA3470.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Starts a SFTP server on port 22
 * @param carbonHome
 */
private void setupSftpServer(String carbonHome) {
    SshServer sshd = SshServer.setUpDefaultServer();
    sshd.setPort(FTP_PORT);
    //sshd.setKeyPairProvider(new FileKeyPairProvider(new String[]{"/home/ravi/WORK/SUPPORT/JIRA/SKYTVNZDEV-26/SftpTest/dist/hostkey.ser"}));
    ClassLoader classLoader = getClass().getClassLoader();
    log.info("Using identity file: " + classLoader.getResource("sftp/id_rsa.pub").getFile());
    File file = new File(classLoader.getResource("sftp/id_rsa.pub").getFile());
    SFTPServer sftpServer = new SFTPServer();
    sshd.setKeyPairProvider(sftpServer.createTestHostKeyProvider(Paths.get(file.getAbsolutePath())));
    sshd.setKeyPairProvider(createTestHostKeyProvider(Paths.get(file.getAbsolutePath())));
    sshd.setUserAuthFactories(
            Arrays.<NamedFactory<UserAuth>>asList(new UserAuthPublicKeyFactory()));
    sshd.setFileSystemFactory(new VirtualFileSystemFactory(Paths.get(carbonHome)));
    sshd.setPublickeyAuthenticator(new PublickeyAuthenticator() {
        public boolean authenticate(String username, PublicKey key, ServerSession session) {
            return "sftpuser".equals(username);
        }
    });

    sshd.setCommandFactory(new ScpCommandFactory());

    sshd.setSubsystemFactories(
            Arrays.<NamedFactory<Command>>asList(new SftpSubsystemFactory()));

    try {
        sshd.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 26
Source Project: ssh-proxy   Source File: SshProxyTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test(timeout = TEST_TIMEOUT_MILLIS)
public void testSingleHop_ConnectionRefused() throws Exception {
	SshServer sshServer = setUpSshServer();
	sshServer.stop();
	try (SshProxy sshProxy = new SshProxy()) {
		sshProxy.connect("localhost", "targethost", 1234);
		fail("SshProxyRuntimeException expected");
	} catch (SshProxyRuntimeException e) {
		log.debug("Expected exception", e);
		assertEquals("Failed to create SSH tunnel to targethost via localhost", e.getMessage());
		assertEquals("Failed to connect to targethost via localhost", e.getCause().getMessage());
	}
}
 
Example 27
Source Project: ssh-proxy   Source File: SshProxyTest.java    License: Apache License 2.0 5 votes vote down vote up
private void tryStop(SshServer sshServer) {
	try {
		log.debug("stopping SSH server");
		sshServer.stop();
	} catch (IOException e) {
		log.error("Failed to stop SSH server", e);
	}
}
 
Example 28
Source Project: aesh-readline   Source File: AsyncAuthTestBase.java    License: Apache License 2.0 5 votes vote down vote up
public void startServer(Integer timeout) throws Exception {
  if (server != null) {
    throw failure("Server already started");
  }
  server = SshServer.setUpDefaultServer();
  if (timeout != null) {
    server.setProperties(Collections.singletonMap(FactoryManager.AUTH_TIMEOUT, timeout.toString()));
  }
  server.setPort(5000);
  server.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(new File("hostkey.ser").toPath()));
  server.setPasswordAuthenticator((username, password, sess) -> authenticator.authenticate(username, password, sess));
  server.setShellFactory(new EchoShellFactory());
  server.setServiceFactories(Arrays.asList(ServerConnectionServiceFactory.INSTANCE, AsyncUserAuthServiceFactory.INSTANCE));
  server.start();
}
 
Example 29
Source Project: datacollector   Source File: TestSshTunnel.java    License: Apache License 2.0 5 votes vote down vote up
private SshServer createSshd(PublickeyAuthenticator publickeyAuthenticator, java.security.KeyPair sshdKeyPair) {
  SshServer sshd = SshServer.setUpDefaultServer();
  sshd.setHost("localhost");
  sshd.setPort(randomPort());

  KeyPairProvider keyPairProvider = KeyPairProvider.wrap(sshdKeyPair);
  sshd.setKeyPairProvider(keyPairProvider);

  sshd.setForwardingFilter(AcceptAllForwardingFilter.INSTANCE);
  sshd.setPublickeyAuthenticator(publickeyAuthenticator);
  return sshd;
}
 
Example 30
Source Project: datacollector   Source File: TestSshTunnel.java    License: Apache License 2.0 5 votes vote down vote up
public void runSshd(PublickeyAuthenticator authenticator, SshCommand command) throws Exception {
  SshServer sshd = createSshd(authenticator, sshdKeyPair);
  try {
    sshd.start();
    command.run(sshd.getHost(), sshd.getPort(), sshdFingerprint, () -> {
      try {
        sshd.stop();
      } catch (Exception ex) {
        throw new RuntimeException("Stopping SSHD: " + ex, ex);
      }
    });
  } finally {
    sshd.stop();
  }
}