public class SshClient extends AbstractFactoryManager implements ClientFactoryManager, ClientSessionCreator, Closeable
Entry point for the client side of the SSH protocol.
The default configured client can be created using
the setUpDefaultClient(). The next step is to
start the client using the start() method.
Sessions can then be created using on of the
connect(String, String, int) or connect(String, java.net.SocketAddress)
methods.
The client can be stopped any time using the stop() method.
Following is an example of using the SshClient:
try (SshClient client = SshClient.setUpDefaultClient()) {
client.start();
try (ClientSession session = client.connect(login, host, port).await().getSession()) {
session.addPasswordIdentity(password);
session.auth().verify(...timeout...);
try (ClientChannel channel = session.createChannel(ClientChannel.CHANNEL_SHELL)) {
channel.setIn(new NoCloseInputStream(System.in));
channel.setOut(new NoCloseOutputStream(System.out));
channel.setErr(new NoCloseOutputStream(System.err));
channel.open();
channel.waitFor(ClientChannel.CLOSED, 0);
} finally {
session.close(false);
}
} finally {
client.stop();
}
}
AbstractCloseable.StateAttributeStore.AttributeKey<T>| Modifier and Type | Field and Description |
|---|---|
protected IoConnector |
connector |
static List<ServiceFactory> |
DEFAULT_SERVICE_FACTORIES |
static Factory<SshClient> |
DEFAULT_SSH_CLIENT_FACTORY |
static List<NamedFactory<UserAuth>> |
DEFAULT_USER_AUTH_FACTORIES
Default user authentication preferences if not set
|
protected SessionFactory |
sessionFactory |
static String |
SSH_CLIENT_PORT_OPTION
Command line option used to indicate non-default target port
|
protected List<NamedFactory<UserAuth>> |
userAuthFactories |
protected UserInteraction |
userInteraction |
agentFactory, channelFactories, channelListenerProxy, channelListeners, executor, fileSystemFactory, globalRequestHandlers, ioServiceFactory, ioServiceFactoryFactory, randomFactory, serviceFactories, sessionListenerProxy, sessionListeners, sessionTimeoutListener, shutdownExecutor, tcpipForwarderFactory, tcpipForwardingFilter, timeoutListenerFuture, tunnelListenerProxy, tunnelListenerscloseFuture, lock, statelogCLIENT_IDENTIFICATION, DEFAULT_HEARTBEAT_INTERVAL, DEFAULT_IGNORE_INVALID_IDENTITIES, DEFAULT_KEEP_ALIVE_HEARTBEAT_STRING, HEARTBEAT_INTERVAL, HEARTBEAT_REQUEST, IGNORE_INVALID_IDENTITIESAUTH_TIMEOUT, CHANNEL_CLOSE_TIMEOUT, DEFAULT_AUTH_TIMEOUT, DEFAULT_CHANNEL_CLOSE_TIMEOUT, DEFAULT_DISCONNECT_TIMEOUT, DEFAULT_IDLE_TIMEOUT, DEFAULT_IGNORE_MESSAGE_FREQUENCY, DEFAULT_IGNORE_MESSAGE_SIZE, DEFAULT_IGNORE_MESSAGE_VARIANCE, DEFAULT_LIMIT_PACKET_SIZE, DEFAULT_MAX_IDENTIFICATION_SIZE, DEFAULT_MAX_PACKET_SIZE, DEFAULT_NIO_WORKERS, DEFAULT_NIO2_MIN_WRITE_TIMEOUT, DEFAULT_NIO2_READ_TIMEOUT, DEFAULT_REKEY_BYTES_LIMIT, DEFAULT_REKEY_PACKETS_LIMIT, DEFAULT_REKEY_TIME_LIMIT, DEFAULT_STOP_WAIT_TIME, DEFAULT_VERSION, DEFAULT_WINDOW_SIZE, DEFAULT_WINDOW_TIMEOUT, DISCONNECT_TIMEOUT, IDLE_TIMEOUT, IGNORE_MESSAGE_FREQUENCY, IGNORE_MESSAGE_SIZE, IGNORE_MESSAGE_VARIANCE, LIMIT_PACKET_SIZE, MAX_IDENTIFICATION_SIZE, MAX_PACKET_SIZE, NIO_WORKERS, NIO2_MIN_WRITE_TIMEOUT, NIO2_READ_BUFFER_SIZE, NIO2_READ_TIMEOUT, REKEY_BLOCKS_LIMIT, REKEY_BYTES_LIMIT, REKEY_PACKETS_LIMIT, REKEY_TIME_LIMIT, SOCKET_BACKLOG, SOCKET_KEEPALIVE, SOCKET_LINGER, SOCKET_RCVBUF, SOCKET_REUSEADDR, SOCKET_SNDBUF, STOP_WAIT_TIME, TCP_NODELAY, WINDOW_SIZE, WINDOW_TIMEOUTEMPTYDEFAULT_PASSWORD_PROMPTS, PASSWORD_PROMPTS, PREFERRED_AUTHSCLOSE_WAIT_TIMEOUT, DEFAULT_CLOSE_WAIT_TIMEOUT| Constructor and Description |
|---|
SshClient() |
addChannelListener, addPortForwardingEventListener, addSessionListener, createSessionTimeoutListener, getAgentFactory, getAttribute, getChannelFactories, getChannelListenerProxy, getFileSystemFactory, getGlobalRequestHandlers, getIoServiceFactory, getIoServiceFactoryFactory, getNioWorkers, getParentPropertyResolver, getPortForwardingEventListenerProxy, getProperties, getRandomFactory, getReservedSessionMessagesHandler, getScheduledExecutorService, getServiceFactories, getSessionListenerProxy, getTcpipForwarderFactory, getTcpipForwardingFilter, getVersion, removeAttribute, removeChannelListener, removePortForwardingEventListener, removeSessionListener, removeSessionTimeout, resolveAttribute, setAgentFactory, setAttribute, setChannelFactories, setFileSystemFactory, setGlobalRequestHandlers, setIoServiceFactoryFactory, setNioWorkers, setParentPropertyResolver, setRandomFactory, setReservedSessionMessagesHandler, setScheduledExecutorService, setScheduledExecutorService, setServiceFactories, setTcpipForwarderFactory, setTcpipForwardingFilter, setupSessionTimeout, stopSessionTimeoutListenergetCipherFactories, getCompressionFactories, getKeyExchangeFactories, getKeyPairProvider, getMacFactories, getSignatureFactories, resolveEffectiveFactories, resolveEffectiveProvider, setCipherFactories, setCompressionFactories, setKeyExchangeFactories, setKeyPairProvider, setMacFactories, setSignatureFactoriesdoCloseGracefully, doCloseImmediatelyaddCloseFutureListener, builder, close, isClosed, isClosing, preClose, removeCloseFutureListenergetSimplifiedLoggerclone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, waitgetAgentFactory, getChannelFactories, getFileSystemFactory, getGlobalRequestHandlers, getIoServiceFactory, getRandomFactory, getScheduledExecutorService, getServiceFactories, getTcpipForwarderFactory, getTcpipForwardingFilter, getVersiongetCipherFactories, getCipherFactoriesNameList, getCipherFactoriesNames, getCompressionFactories, getCompressionFactoriesNameList, getCompressionFactoriesNames, getKeyExchangeFactories, getMacFactories, getMacFactoriesNameList, getMacFactoriesNames, setCipherFactories, setCipherFactoriesNameList, setCipherFactoriesNames, setCipherFactoriesNames, setCompressionFactories, setCompressionFactoriesNameList, setCompressionFactoriesNames, setCompressionFactoriesNames, setKeyExchangeFactories, setMacFactories, setMacFactoriesNameList, setMacFactoriesNames, setMacFactoriesNamesgetKeyPairProvider, setKeyPairProvidergetSignatureFactories, getSignatureFactories, getSignatureFactoriesNameList, getSignatureFactoriesNames, resolveSignatureFactories, setSignatureFactories, setSignatureFactoriesNameList, setSignatureFactoriesNames, setSignatureFactoriesNamesaddSessionListener, getSessionListenerProxy, removeSessionListenergetReservedSessionMessagesHandler, setReservedSessionMessagesHandleraddChannelListener, getChannelListenerProxy, removeChannelListeneraddPortForwardingEventListener, getPortForwardingEventListenerProxy, removePortForwardingEventListenergetAttribute, removeAttribute, resolveAttribute, resolveAttribute, resolveAttribute, resolveAttribute, setAttributegetBoolean, getBooleanProperty, getInteger, getIntProperty, getLong, getLongProperty, getObject, getParentPropertyResolver, getProperties, getString, getStringPropertygetUserAuthFactoriesNameList, getUserAuthFactoriesNames, setUserAuthFactoriesNameList, setUserAuthFactoriesNames, setUserAuthFactoriesNamesaddCloseFutureListener, close, close, close, getMaxCloseWaitTime, isClosed, isClosing, isOpen, removeCloseFutureListenerpublic static final String SSH_CLIENT_PORT_OPTION
public static final List<NamedFactory<UserAuth>> DEFAULT_USER_AUTH_FACTORIES
public static final List<ServiceFactory> DEFAULT_SERVICE_FACTORIES
protected IoConnector connector
protected SessionFactory sessionFactory
protected UserInteraction userInteraction
protected List<NamedFactory<UserAuth>> userAuthFactories
public SessionFactory getSessionFactory()
public void setSessionFactory(SessionFactory sessionFactory)
public ClientProxyConnector getClientProxyConnector()
getClientProxyConnector in interface ClientProxyConnectorHolderpublic void setClientProxyConnector(ClientProxyConnector proxyConnector)
setClientProxyConnector in interface ClientProxyConnectorHolderpublic ScpFileOpener getScpFileOpener()
getScpFileOpener in interface ScpFileOpenerHolderScpFileOpener set via call
to ScpFileOpenerHolder.setScpFileOpener(ScpFileOpener)public void setScpFileOpener(ScpFileOpener opener)
setScpFileOpener in interface ScpFileOpenerHolderopener - The default ScpFileOpener to use - if null
then a default opener is usedpublic ServerKeyVerifier getServerKeyVerifier()
ClientAuthenticationManagergetServerKeyVerifier in interface ClientAuthenticationManagerServerKeyVerifier to use - never nullpublic void setServerKeyVerifier(ServerKeyVerifier serverKeyVerifier)
setServerKeyVerifier in interface ClientAuthenticationManagerpublic HostConfigEntryResolver getHostConfigEntryResolver()
getHostConfigEntryResolver in interface ClientFactoryManagerHostConfigEntryResolver to use in order to resolve the
effective session parameters - never nullpublic void setHostConfigEntryResolver(HostConfigEntryResolver resolver)
setHostConfigEntryResolver in interface ClientFactoryManagerpublic FilePasswordProvider getFilePasswordProvider()
getFilePasswordProvider in interface ClientFactoryManagerFilePasswordProvider to use if need to load encrypted
identities keys - never nullFilePasswordProvider.EMPTYpublic void setFilePasswordProvider(FilePasswordProvider provider)
setFilePasswordProvider in interface ClientFactoryManagerpublic ClientIdentityLoader getClientIdentityLoader()
getClientIdentityLoader in interface ClientFactoryManagerClientIdentityLoader to use in order to load client
key pair identities - never nullpublic void setClientIdentityLoader(ClientIdentityLoader loader)
setClientIdentityLoader in interface ClientFactoryManagerpublic UserInteraction getUserInteraction()
getUserInteraction in interface ClientAuthenticationManagerUserInteraction object to communicate with the user
(may be null to indicate that no such communication is allowed)public void setUserInteraction(UserInteraction userInteraction)
setUserInteraction in interface ClientAuthenticationManagerpublic List<NamedFactory<UserAuth>> getUserAuthFactories()
getUserAuthFactories in interface ClientAuthenticationManagerList of UserAuth NamedFactory-ies - never
null/emptypublic void setUserAuthFactories(List<NamedFactory<UserAuth>> userAuthFactories)
setUserAuthFactories in interface ClientAuthenticationManagerpublic AuthenticationIdentitiesProvider getRegisteredIdentities()
getRegisteredIdentities in interface ClientAuthenticationManagerAuthenticationIdentitiesProvider to be used for attempting
password or public key authenticationpublic PasswordIdentityProvider getPasswordIdentityProvider()
ClientAuthenticationManagerPasswordIdentityProvider used to provide password
candidatesgetPasswordIdentityProvider in interface ClientAuthenticationManagerPasswordIdentityProvider instance - ignored if null
(i.e., no passwords available)public void setPasswordIdentityProvider(PasswordIdentityProvider provider)
setPasswordIdentityProvider in interface ClientAuthenticationManagerpublic void addPasswordIdentity(String password)
addPasswordIdentity in interface ClientAuthenticationManagerpassword - Password to be added - may not be null/empty.
Note: this password is in addition to whatever passwords
are available via the PasswordIdentityProvider (if any)public String removePasswordIdentity(String password)
removePasswordIdentity in interface ClientAuthenticationManagerpassword - The password to remove - ignored if null/emptyClientAuthenticationManager.addPasswordIdentity(String) - or null if no
match foundpublic void addPublicKeyIdentity(KeyPair kp)
addPublicKeyIdentity in interface ClientAuthenticationManagerkp - The KeyPair to add - may not be null
Note: this key is in addition to whatever keys
are available via the KeyIdentityProvider (if any)public KeyPair removePublicKeyIdentity(KeyPair kp)
removePublicKeyIdentity in interface ClientAuthenticationManagerkp - The KeyPair to remove - ignored if nullKeyPair - same one that was added via
ClientAuthenticationManager.addPublicKeyIdentity(KeyPair) - or null if no
match foundprotected void checkConfig()
checkConfig in class AbstractFactoryManagerpublic void start()
public void stop()
public void open()
throws IOException
IOExceptionprotected Closeable getInnerCloseable()
getInnerCloseable in class AbstractInnerCloseablepublic ConnectFuture connect(String username, String host, int port) throws IOException
ClientSessionCreatorHostConfigEntry and connects to itconnect in interface ClientSessionCreatorusername - The intended usernamehost - The target host name/address - never null/emptyport - The target portConnectFutureIOException - If failed to resolve the effective target or
connect to itClientSessionCreator.connect(HostConfigEntry)public ConnectFuture connect(String username, SocketAddress address) throws IOException
ClientSessionCreatorHostConfigEntry and connects to itconnect in interface ClientSessionCreatorusername - The intended usernameaddress - The intended SocketAddress - never null. If
this is an InetSocketAddress then the effective HostConfigEntry
is resolved and used.ConnectFutureIOException - If failed to resolve the effective target or
connect to itClientSessionCreator.connect(HostConfigEntry)public ConnectFuture connect(HostConfigEntry hostConfig) throws IOException
connect in interface ClientSessionCreatorhostConfig - The effective HostConfigEntry to connect to - never nullConnectFutureIOException - If failed to create the connection futureprotected List<KeyPair> loadClientIdentities(Collection<String> locations, LinkOption... options) throws IOException
IOExceptionprotected ConnectFuture doConnect(String username, SocketAddress address, Collection<? extends KeyPair> identities, boolean useDefaultIdentities) throws IOException
IOExceptionprotected SshFutureListener<IoConnectFuture> createConnectCompletionListener(ConnectFuture connectFuture, String username, SocketAddress address, Collection<? extends KeyPair> identities, boolean useDefaultIdentities)
protected void onConnectOperationComplete(IoSession ioSession, ConnectFuture connectFuture, String username, SocketAddress address, Collection<? extends KeyPair> identities, boolean useDefaultIdentities)
protected void setupDefaultSessionIdentities(ClientSession session)
protected IoConnector createConnector()
protected SessionFactory createSessionFactory()
public static SimpleClient setUpDefaultSimpleClient()
SimpleClientSimpleClient wrapper. Note: when the wrapper
is closed the client is also stoppedsetUpDefaultClient(),
wrapAsSimpleClient(SshClient)public static SimpleClient wrapAsSimpleClient(SshClient client)
SshClient instance as a SimpleClientclient - The client instance - never null. Note:
client must be started before the simple client wrapper is used.SimpleClient wrapper. Note: when the
wrapper is closed the client is also stoppedpublic static SshClient setUpDefaultClient()
public static boolean showError(PrintStream stderr, String message)
public static ClientSession setupClientSession(String portOption, BufferedReader stdin, PrintStream stdout, PrintStream stderr, String... args) throws Exception
Exceptionpublic static Path resolveIdentityFile(String id) throws IOException
IOExceptionpublic static SshClient setupClient(Map<String,?> options, List<NamedFactory<Cipher>> ciphers, List<NamedFactory<Mac>> macs, List<NamedFactory<Compression>> compressions, Collection<? extends Path> identities, BufferedReader stdin, PrintStream stdout, PrintStream stderr) throws Exception
Exceptionpublic static FileKeyPairProvider setupSessionIdentities(ClientFactoryManager client, Collection<? extends Path> identities, BufferedReader stdin, PrintStream stdout, PrintStream stderr) throws Throwable
Throwablepublic static UserInteraction setupSessionUserInteraction(ClientAuthenticationManager client, BufferedReader stdin, PrintStream stdout, PrintStream stderr)
public static ServerKeyVerifier setupServerKeyVerifier(ClientAuthenticationManager manager, Map<String,?> options, BufferedReader stdin, PrintStream stdout, PrintStream stderr)
public static OutputStream resolveLoggingTargetStream(PrintStream stdout, PrintStream stderr, String... args)
public static OutputStream resolveLoggingTargetStream(PrintStream stdout, PrintStream stderr, String[] args, int maxIndex)
public static List<NamedFactory<Compression>> setupCompressions(Map<String,?> options, PrintStream stderr)
public static List<NamedFactory<Compression>> setupCompressions(String argName, String argVal, List<NamedFactory<Compression>> current, PrintStream stderr)
public static List<NamedFactory<Mac>> setupMacs(Map<String,?> options, PrintStream stderr)
public static List<NamedFactory<Mac>> setupMacs(String argName, String argVal, List<NamedFactory<Mac>> current, PrintStream stderr)
public static List<NamedFactory<Cipher>> setupCiphers(Map<String,?> options, PrintStream stderr)
public static List<NamedFactory<Cipher>> setupCiphers(String argName, String argVal, List<NamedFactory<Cipher>> current, PrintStream stderr)
public static Handler setupLogging(Level level, PrintStream stdout, PrintStream stderr, OutputStream outputStream)
Copyright © 2008–2017 The Apache Software Foundation. All rights reserved.