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

The following examples show how to use org.apache.sshd.server.Command. 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: WindowAdjustTest.java    License: 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 Project: termd   Source File: SshTtyTestBase.java    License: 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 4
Source Project: java-examples   Source File: EmbeddedSftpServer.java    License: 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 5
Source Project: java-examples   Source File: EmbeddedSftpServer.java    License: 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 6
Source Project: sftp-fs   Source File: FixedSftpSubsystem.java    License: 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 Project: termd   Source File: WindowAdjustTest.java    License: 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 8
/**
 * 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 9
Source Project: pentaho-kettle   Source File: SftpServer.java    License: 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 10
Source Project: sftp-fs   Source File: FixedSftpSubsystem.java    License: 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 11
Source Project: gameserver   Source File: MyCommandFactory.java    License: 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 12
Source Project: artifactory_ssh_proxy   Source File: SshdProxySettings.java    License: 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 13
/**
 * 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 Project: ExpectIt   Source File: SshEchoCommandFactory.java    License: 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 15
Source Project: nifi   Source File: SSHTestServer.java    License: 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 16
Source Project: termd   Source File: KeepAliveTest.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Command create() {
    return new TestEchoShell();
}
 
Example 17
Source Project: termd   Source File: UnknownCommandFactory.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Command createCommand(String command) {
    return new UnknownCommand(command);
}
 
Example 18
Source Project: termd   Source File: AsyncEchoShellFactory.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Command create() {
    return new EchoShell();
}
 
Example 19
Source Project: termd   Source File: EchoShellFactory.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Command create() {
    return new EchoShell();
}
 
Example 20
Source Project: termd   Source File: WindowTest.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Command create() {
    return new TestEchoShell();
}
 
Example 21
Source Project: aesh-readline   Source File: EchoShellFactory.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Command create() {
    return new EchoShell();
}
 
Example 22
@BeforeClass
public static void startSSHServer() throws Exception {
    // Disable bouncy castle to avoid versions conflict
    System.setProperty("org.apache.sshd.registerBouncyCastle", "false");

    sshd = SshServer.setUpDefaultServer();

    SimpleGeneratorHostKeyProvider keyProvider = new SimpleGeneratorHostKeyProvider();
    keyProvider.setAlgorithm("RSA");
    sshd.setKeyPairProvider(keyProvider);

    List<NamedFactory<UserAuth>> userAuthFactories = new ArrayList<>(1);
    userAuthFactories.add(new UserAuthPasswordFactory());
    sshd.setUserAuthFactories(userAuthFactories);

    sshd.setPasswordAuthenticator(new PasswordAuthenticator() {
        @Override
        public boolean authenticate(String username, String password, ServerSession session) {
            return username != null && username.equals(password);
        }
    });

    CommandFactory cf = new CommandFactory() {
        @Override
        public Command createCommand(String command) {
            String[] splitCommand;
            if (OsUtils.isUNIX()) {
                splitCommand = SSHInfrastructureHelper.splitCommand(command);
            } else if (OsUtils.isWin32()) {
                splitCommand = SSHInfrastructureHelper.splitCommandWithoutRemovingQuotes(command);
            } else {
                throw new IllegalStateException("Operating system is not recognized");
            }
            StringBuilder rebuiltCommand = new StringBuilder();
            for (String commandPiece : splitCommand) {
                rebuiltCommand.append(commandPiece).append(" ");
            }
            rebuiltCommand.trimToSize();

            if (OsUtils.isUNIX()) {
                return new ProcessShellFactory(new String[] { "/bin/sh", "-c",
                                                              rebuiltCommand.toString() }).create();
            } else {
                return new ProcessShellFactory(new String[] { "cmd.exe", "/C",
                                                              rebuiltCommand.toString() }).create();
            }
        }
    };

    sshd.setCommandFactory(cf);

    sshd.start();

    port = sshd.getPort();

    javaExePath = System.getProperty("java.home") + File.separator + "bin" + File.separator +
                  (OsUtils.isWin32() ? "java.exe" : "java");
    javaExePath = "\"" + javaExePath + "\"";

    infraParams = new Object[] { ("localhost " + NB_NODES + "\n").getBytes(), //hosts
                                 60000, //timeout
                                 0, //attempts
                                 10, //wait between failures
                                 port, //ssh server port
                                 "toto", //ssh username
                                 "toto", //ssh password
                                 new byte[0], // optional ssh private key
                                 new byte[0], // optional ssh options file
                                 javaExePath, //java path on the remote machines
                                 PAResourceManagerProperties.RM_HOME.getValueAsString(), //Scheduling path on remote machines
                                 OperatingSystem.getOperatingSystem(), "" }; // extra java options

    policyParameters = new Object[] { AccessType.ALL.toString(), AccessType.ALL.toString(), "20000" };

}
 
Example 23
Source Project: termd   Source File: KeepAliveTest.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Command create() {
    return new TestEchoShell();
}
 
Example 24
Source Project: termd   Source File: UnknownCommandFactory.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Command createCommand(String command) {
    return new UnknownCommand(command);
}
 
Example 25
Source Project: termd   Source File: AsyncEchoShellFactory.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Command create() {
    return new EchoShell();
}
 
Example 26
Source Project: termd   Source File: EchoShellFactory.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Command create() {
    return new EchoShell();
}
 
Example 27
Source Project: termd   Source File: WindowTest.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Command create() {
    return new TestEchoShell();
}
 
Example 28
Source Project: gameserver   Source File: ReloadCommandFactory.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Command createCommand(String command) {
	return delegate.createCommand(command);
}
 
Example 29
@Override
public Command create() {
    return new ForwardingShellWrapper(ttyOptions);
}
 
Example 30
Source Project: artifactory_ssh_proxy   Source File: GroovyShellFactory.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Command create() {
    return new GroovyShellWrapper(ttyOptions);
}