org.apache.sshd.server.Command Java Examples

The following examples show how to use org.apache.sshd.server.Command. 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 File: EmbeddedSftpServer.java    From java-examples with MIT License 7 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
    final PublicKey allowedKey = decodePublicKey();
    this.server.setPublickeyAuthenticator(new PublickeyAuthenticator() {

        @Override
        public boolean authenticate(String username, PublicKey key, ServerSession session) {
            return key.equals(allowedKey);
        }

    });
    this.server.setPort(this.port);
    this.server.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(Files.createTempFile("host_file", ".ser")));
    this.server.setSubsystemFactories(Collections.<NamedFactory<Command>>singletonList(new SftpSubsystemFactory()));
    server.setFileSystemFactory(new VirtualFileSystemFactory(Files.createTempDirectory("SFTP_TEMP")));
    server.setCommandFactory(new ScpCommandFactory());
}
 
Example #2
Source File: WindowAdjustTest.java    From termd with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    sshServer = setupTestServer();

    final byte[] msg = Files.readAllBytes(
            Paths.get(getClass().getResource("/big-msg.txt").toURI()));
    sshServer.setShellFactory(new Factory<Command>() {
        @Override
        public Command create() {
            return new FloodingAsyncCommand(msg, BIG_MSG_SEND_COUNT, END_FILE);
        }
    });

    sshServer.setKeyPairProvider(new SimpleGeneratorHostKeyProvider());
    sshServer.start();
    port = sshServer.getPort();
}
 
Example #3
Source File: SftpServer.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
private SshServer createSshServer( int port, String homeDir, String hostKeyPath ) {
  SshServer server = SshServer.setUpDefaultServer();
  server.setHost( "localhost" );
  server.setPort( port );
  server.setFileSystemFactory( new VirtualFileSystemFactory( homeDir ) );
  server.setSubsystemFactories( Collections.<NamedFactory<Command>>singletonList( new SftpSubsystem.Factory() ) );
  server.setCommandFactory( new ScpCommandFactory() );
  server.setKeyPairProvider( new SimpleGeneratorHostKeyProvider( hostKeyPath ) );
  server.setPasswordAuthenticator( this );
  return server;
}
 
Example #4
Source File: DefaultScpCommandFactory.java    From artifactory_ssh_proxy with Apache License 2.0 6 votes vote down vote up
/**
 * Parses a command string and verifies that the basic syntax is correct. If parsing fails the responsibility is
 * delegated to the configured {@link CommandFactory} instance; if one exist.
 * 
 * @param command command to parse
 * @return configured {@link Command} instance
 * @throws IllegalArgumentException
 */
@Override
public Command createCommand(String command) {
    try {
        if (command.startsWith("scp")) {
            NewScpCommand newScpCommand = new NewScpCommand(command, requestLog, envToAfPropertyMapping);
            return newScpCommand;
        }

        if (command.startsWith("mkdir")) {
            return new MkdirCommand(splitCommandString("mkdir", command));
        }
    } catch (IllegalArgumentException iae) {
        if (delegate != null) {
            return delegate.createCommand(command);
        }
        throw iae;
    }

    throw new IllegalArgumentException("invalid command: " + command);
}
 
Example #5
Source File: WindowAdjustTest.java    From termd with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    sshServer = setupTestServer();

    final byte[] msg = Files.readAllBytes(
            Paths.get(getClass().getResource("/big-msg.txt").toURI()));
    sshServer.setShellFactory(new Factory<Command>() {
        @Override
        public Command create() {
            return new FloodingAsyncCommand(msg, BIG_MSG_SEND_COUNT, END_FILE);
        }
    });

    sshServer.setKeyPairProvider(new SimpleGeneratorHostKeyProvider());
    sshServer.start();
    port = sshServer.getPort();
}
 
Example #6
Source File: FixedSftpSubsystem.java    From sftp-fs with Apache License 2.0 6 votes vote down vote up
@Override
public Command create() {
    SftpSubsystem subsystem = new FixedSftpSubsystem(getExecutorService(), isShutdownOnExit(), getUnsupportedAttributePolicy(),
            getFileSystemAccessor(), getErrorStatusDataHandler());
    Collection<? extends SftpEventListener> listeners = getRegisteredListeners();
    if (GenericUtils.size(listeners) > 0) {
        for (SftpEventListener l : listeners) {
            subsystem.addSftpEventListener(l);
        }
    }
    subsystem.addSftpEventListener(new AbstractSftpEventListenerAdapter() {
        @Override
        public void open(ServerSession session, String remoteHandle, Handle localHandle) {
            if (localHandle instanceof DirectoryHandle) {
                DirectoryHandle directoryHandle = (DirectoryHandle) localHandle;
                directoryHandle.markDotSent();
                directoryHandle.markDotDotSent();
            }
        }
    });

    return subsystem;
}
 
Example #7
Source File: EmbeddedSftpServer.java    From java-examples with MIT License 6 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
    final PublicKey allowedKey = decodePublicKey();
    this.server.setPublickeyAuthenticator(new PublickeyAuthenticator() {

        @Override
        public boolean authenticate(String username, PublicKey key, ServerSession session) {
            return key.equals(allowedKey);
        }

    });
    this.server.setPort(this.port);
    this.server.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(Files.createTempFile("host_file", ".ser")));
    this.server.setSubsystemFactories(Collections.<NamedFactory<Command>>singletonList(new SftpSubsystemFactory()));
    server.setFileSystemFactory(new VirtualFileSystemFactory(Files.createTempDirectory("SFTP_TEMP")));
    server.setCommandFactory(new ScpCommandFactory());
}
 
Example #8
Source File: NettySshTtyBootstrap.java    From termd with 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 #9
Source File: SshTtyTestBase.java    From termd with Apache License 2.0 6 votes vote down vote up
@Override
protected void server(final Consumer<TtyConnection> onConnect) {
  if (sshd != null) {
    throw failure("Already a server");
  }
  try {
    sshd = createServer();
    sshd.setPort(5000);
    sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(new File("hostkey.ser").toPath()));
    sshd.setPasswordAuthenticator(new PasswordAuthenticator() {
      @Override
      public boolean authenticate(String username, String password, ServerSession session) throws PasswordChangeRequiredException {
        return true;
      }
    });
    sshd.setShellFactory(new Factory<Command>() {
      @Override
      public Command create() {
        return createConnection(onConnect);
      }
    });
    sshd.start();
  } catch (Exception e) {
    throw failure(e);
  }
}
 
Example #10
Source File: SshdProxySettings.java    From artifactory_ssh_proxy with Apache License 2.0 5 votes vote down vote up
@Override
public Factory<Command> getShellFactory() {
    EnumSet<TtyOptions> ttyOptions;

    if (OsUtils.isUNIX()) {
        /**
         * org.apache.sshd.server.shell.ProcessShellFactory does this: ttyOptions = EnumSet.of(TtyOptions.ONlCr);
         * 
         * However, it doesn't seem to work for me. So in our copy of
         * org.apache.sshd.server.shell.TtyFilterOutputStream.TtyFilterOutputStream(EnumSet<TtyOptions>,
         * OutputStream, TtyFilterInputStream), we have a special hack that if TtyOptions.INlCr and TtyOptions.ICrNl
         * are both set, send cr nl instead. no idea if the windows even works.
         */
        // ttyOptions = EnumSet.of(TtyOptions.ONlCr);
        ttyOptions = EnumSet.of(TtyOptions.OCrNl, TtyOptions.INlCr, TtyOptions.ICrNl);
    } else {
        ttyOptions = EnumSet.of(TtyOptions.Echo, TtyOptions.OCrNl, TtyOptions.INlCr, TtyOptions.ICrNl);
    }

    switch (shellMode) {
        case FORWARDING_ECHO_SHELL:
            return new ForwardingShellFactory(ttyOptions);

        case GROOVY_SHELL:
            return new GroovyShellFactory(ttyOptions);

        case MESSAGE:
        default:
            // TODO when separating out settings, we'll provide a different success
            // message, or a file path for it.
            return new MessageShellFactory(SshProxyMessage.MESSAGE_STRING);
    }
}
 
Example #11
Source File: SSHTestServer.java    From nifi with Apache License 2.0 5 votes vote down vote up
public void startServer() throws IOException {
    sshd = SshServer.setUpDefaultServer();
    sshd.setHost("localhost");

    sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider());

    //Accept all keys for authentication
    sshd.setPublickeyAuthenticator((s, publicKey, serverSession) -> true);

    //Allow username/password authentication using pre-defined credentials
    sshd.setPasswordAuthenticator((username, password, serverSession) ->  this.username.equals(username) && this.password.equals(password));

    //Setup Virtual File System (VFS)
    //Ensure VFS folder exists
    Path dir = Paths.get(getVirtualFileSystemPath());
    Files.createDirectories(dir);
    sshd.setFileSystemFactory(new VirtualFileSystemFactory(dir.toAbsolutePath()));

    //Add SFTP support
    List<NamedFactory<Command>> sftpCommandFactory = new ArrayList<>();
    sftpCommandFactory.add(new SftpSubsystemFactory());
    sshd.setSubsystemFactories(sftpCommandFactory);

    sshd.start();
}
 
Example #12
Source File: SshEchoCommandFactory.java    From ExpectIt with Apache License 2.0 5 votes vote down vote up
@Override
public Command create() {
    return new Command() {
        @Override
        public void setInputStream(InputStream in) {
            SshEchoCommandFactory.this.in = in;
        }

        @Override
        public void setOutputStream(OutputStream out) {
            SshEchoCommandFactory.this.out = out;
        }

        @Override
        public void setErrorStream(OutputStream err) {

        }

        @Override
        public void setExitCallback(ExitCallback callback) {

        }

        @Override
        public void start(Environment env) throws IOException {
            executor.scheduleWithFixedDelay(
                    SshEchoCommandFactory.this,
                    0,
                    100,
                    TimeUnit.MILLISECONDS);
        }

        @Override
        public void destroy() {
            executor.shutdownNow();
        }
    };
}
 
Example #13
Source File: NullScpCommandFactory.java    From artifactory_ssh_proxy with Apache License 2.0 5 votes vote down vote up
/**
 * Parses a command string and verifies that the basic syntax is correct. If parsing fails the responsibility is
 * delegated to the configured {@link CommandFactory} instance; if one exist.
 * 
 * @param command command to parse
 * @return configured {@link Command} instance
 * @throws IllegalArgumentException
 */
@Override
public Command createCommand(String command) {
    try {
        return new NullScpCommand(command);
    } catch (IllegalArgumentException iae) {
        if (delegate != null) {
            return delegate.createCommand(command);
        }
        throw iae;
    }
}
 
Example #14
Source File: MyCommandFactory.java    From gameserver with Apache License 2.0 5 votes vote down vote up
@Override
public Command createCommand(String command) {
	if ( command.equals("admin") ) {
		return new AdminCommand();
	}
	return null;
}
 
Example #15
Source File: FixedSftpSubsystem.java    From sftp-fs with Apache License 2.0 5 votes vote down vote up
@Override
public Command create() {
    SftpSubsystem subsystem = new FixedSftpSubsystem(getExecutorService(), isShutdownOnExit(), getUnsupportedAttributePolicy(),
            getFileSystemAccessor(), getErrorStatusDataHandler());
    Collection<? extends SftpEventListener> listeners = getRegisteredListeners();
    if (GenericUtils.size(listeners) > 0) {
        for (SftpEventListener l : listeners) {
            subsystem.addSftpEventListener(l);
        }
    }

    return subsystem;
}
 
Example #16
Source File: MessageShellFactory.java    From artifactory_ssh_proxy with Apache License 2.0 4 votes vote down vote up
@Override
public Command create() {
    return new InvertedShellWrapper(createShell());
}
 
Example #17
Source File: WindowTest.java    From termd with Apache License 2.0 4 votes vote down vote up
@Override
public Command create() {
    return new TestEchoShell();
}
 
Example #18
Source File: ConsoleShellFactory.java    From Bukkit-SSHD with Apache License 2.0 4 votes vote down vote up
public Command create() {
    return new ConsoleShell();
}
 
Example #19
Source File: ConsoleShellFactory.java    From Bukkit-SSHD with Apache License 2.0 4 votes vote down vote up
public Command get() {
    return this.create();
}
 
Example #20
Source File: ConsoleCommandFactory.java    From Bukkit-SSHD with Apache License 2.0 4 votes vote down vote up
@Override
public Command createCommand(String command) {
    return new ConsoleCommand(command);
}
 
Example #21
Source File: EchoShellFactory.java    From termd with Apache License 2.0 4 votes vote down vote up
@Override
public Command create() {
    return new EchoShell();
}
 
Example #22
Source File: NetconfSessionMinaImplTest.java    From onos with Apache License 2.0 4 votes vote down vote up
@BeforeClass
public static void setUp() throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    int portNumber = TestTools.findAvailablePort(50830);
    sshServerNetconf = SshServer.setUpDefaultServer();
    sshServerNetconf.setPasswordAuthenticator(
            new PasswordAuthenticator() {
                @Override
                public boolean authenticate(
                        String username,
                        String password,
                        ServerSession session) {
                    return TEST_USERNAME.equals(username) && TEST_PASSWORD.equals(password);
                }
            });

    TestUtils.setField(NetconfSessionMinaImpl.class, "directory", TEST_DIRECTORY);

    sshServerNetconf.setPort(portNumber);
    SimpleGeneratorHostKeyProvider provider = new SimpleGeneratorHostKeyProvider();
    provider.setFile(new File(TEST_SERFILE));
    sshServerNetconf.setKeyPairProvider(provider);
    sshServerNetconf.setSubsystemFactories(
            Arrays.<NamedFactory<Command>>asList(new NetconfSshdTestSubsystem.Factory()));
    sshServerNetconf.open();
    log.info("SSH Server opened on port {}", portNumber);

    NetconfDeviceInfo deviceInfo = new NetconfDeviceInfo(
            TEST_USERNAME, TEST_PASSWORD, Ip4Address.valueOf(TEST_HOSTNAME), portNumber);
    deviceInfo.setConnectTimeoutSec(OptionalInt.of(30));
    deviceInfo.setReplyTimeoutSec(OptionalInt.of(30));

    session1 = new NetconfSessionMinaImpl(deviceInfo, ImmutableList.of("urn:ietf:params:netconf:base:1.0"));
    log.info("Started NETCONF Session {} with test SSHD server in Unit Test", session1.getSessionId());
    assertTrue("Incorrect sessionId", !session1.getSessionId().equalsIgnoreCase("-1"));
    assertTrue("Incorrect sessionId", !session1.getSessionId().equalsIgnoreCase("0"));
    assertThat(session1.getDeviceCapabilitiesSet(), containsInAnyOrder(DEFAULT_CAPABILITIES.toArray()));

    session2 = new NetconfSessionMinaImpl(deviceInfo, ImmutableList.of("urn:ietf:params:netconf:base:1.0"));
    log.info("Started NETCONF Session {} with test SSHD server in Unit Test", session2.getSessionId());
    assertTrue("Incorrect sessionId", !session2.getSessionId().equalsIgnoreCase("-1"));
    assertTrue("Incorrect sessionId", !session2.getSessionId().equalsIgnoreCase("0"));
    assertThat(session2.getDeviceCapabilitiesSet(), containsInAnyOrder(DEFAULT_CAPABILITIES.toArray()));

    session3 = new NetconfSessionMinaImpl(deviceInfo);
    log.info("Started NETCONF Session {} with test SSHD server in Unit Test", session3.getSessionId());
    assertTrue("Incorrect sessionId", !session3.getSessionId().equalsIgnoreCase("-1"));
    assertTrue("Incorrect sessionId", !session3.getSessionId().equalsIgnoreCase("0"));
    assertThat(session3.getDeviceCapabilitiesSet(), containsInAnyOrder(DEFAULT_CAPABILITIES_1_1.toArray()));

    session4 = new NetconfSessionMinaImpl(deviceInfo);
    log.info("Started NETCONF Session {} with test SSHD server in Unit Test", session4.getSessionId());
    assertTrue("Incorrect sessionId", !session4.getSessionId().equalsIgnoreCase("-1"));
    assertTrue("Incorrect sessionId", !session4.getSessionId().equalsIgnoreCase("0"));
    assertThat(session4.getDeviceCapabilitiesSet(), containsInAnyOrder(DEFAULT_CAPABILITIES_1_1.toArray()));
}
 
Example #23
Source File: NetconfSshdTestSubsystem.java    From onos with Apache License 2.0 4 votes vote down vote up
@Override
public Command create() {
    return new NetconfSshdTestSubsystem(getExecutorService(), isShutdownOnExit());
}
 
Example #24
Source File: SshdServerMock.java    From gerrit-events with MIT License 4 votes vote down vote up
@Override
public Command createCommand(String s) {
    CommandMock command = findAndCreateCommand(s);
    return setCurrentCommand(command);
}
 
Example #25
Source File: TestChainedFactories.java    From artifactory_ssh_proxy with Apache License 2.0 4 votes vote down vote up
@Override
public Command createCommand(String command) {
    return null;
}
 
Example #26
Source File: AsyncEchoShellFactory.java    From termd with Apache License 2.0 4 votes vote down vote up
@Override
public Command create() {
    return new EchoShell();
}
 
Example #27
Source File: KeepAliveTest.java    From termd with Apache License 2.0 4 votes vote down vote up
@Override
public Command create() {
    return new TestEchoShell();
}
 
Example #28
Source File: UnknownCommandFactory.java    From termd with Apache License 2.0 4 votes vote down vote up
@Override
public Command createCommand(String command) {
    return new UnknownCommand(command);
}
 
Example #29
Source File: GroovyShellFactory.java    From artifactory_ssh_proxy with Apache License 2.0 4 votes vote down vote up
@Override
public Command create() {
    return new GroovyShellWrapper(ttyOptions);
}
 
Example #30
Source File: ForwardingShellFactory.java    From artifactory_ssh_proxy with Apache License 2.0 4 votes vote down vote up
@Override
public Command create() {
    return new ForwardingShellWrapper(ttyOptions);
}