public class SshClient extends AbstractFactoryManager implements ClientFactoryManager, 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 configure
and then start the client using the start()
method.
Sessions can then be created using on of the ClientSessionCreator.connect(String, String, int)
or
ClientSessionCreator.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()) {
...further configuration of the client...
client.start();
try (ClientSession session = client.connect(login, host, port)
.verify(...timeout...)
.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();
}
}
Note: the idea is to have one SshClient
instance for the entire application and re-use it
repeatedly in order to create as many sessions as necessary - possibly with different hosts, ports, users, passwords,
etc. - including concurrently. In other words, except for exceptional cases, it is recommended to initialize
one instance of SshClient
for the application and then use throughout - including for multi-threading. As
long as the SshClient
is not re-configured it should be multi-thread safe regardless of the target session
being created.AbstractCloseable.State
AttributeRepository.AttributeKey<T>
SessionHeartbeatController.HeartbeatType
Modifier and Type | Field and Description |
---|---|
protected IoConnector |
connector |
static List<ServiceFactory> |
DEFAULT_SERVICE_FACTORIES |
static Factory<SshClient> |
DEFAULT_SSH_CLIENT_FACTORY |
static List<UserAuthFactory> |
DEFAULT_USER_AUTH_FACTORIES
Default user authentication preferences if not set
|
protected SessionFactory |
sessionFactory |
protected List<UserAuthFactory> |
userAuthFactories |
agentFactory, channelFactories, channelListenerProxy, channelListeners, executor, fileSystemFactory, forwarderFactory, forwardingFilter, globalRequestHandlers, ioServiceFactory, ioServiceFactoryFactory, randomFactory, serviceFactories, sessionListenerProxy, sessionListeners, sessionTimeoutListener, shutdownExecutor, timeoutListenerFuture, tunnelListenerProxy, tunnelListeners
closeFuture, futureLock, state
log
DEFAULT_VERSION
NONE
EMPTY
TARGET_SERVER
Constructor and Description |
---|
SshClient() |
addChannelListener, addPortForwardingEventListener, addSessionListener, attributeKeys, clearAttributes, computeAttributeIfAbsent, createSessionTimeoutListener, getAgentFactory, getAttribute, getAttributesCount, getChannelFactories, getChannelListenerProxy, getChannelStreamWriterResolver, getFileSystemFactory, getForwarderFactory, getForwardingFilter, getGlobalRequestHandlers, getIoServiceEventListener, getIoServiceFactory, getIoServiceFactoryFactory, getNioWorkers, getParentPropertyResolver, getPortForwardingEventListenerProxy, getProperties, getRandomFactory, getReservedSessionMessagesHandler, getScheduledExecutorService, getServiceFactories, getSessionDisconnectHandler, getSessionListenerProxy, getUnknownChannelReferenceHandler, getVersion, removeAttribute, removeChannelListener, removePortForwardingEventListener, removeSessionListener, removeSessionTimeout, resolveUnknownChannelReferenceHandler, setAgentFactory, setAttribute, setChannelFactories, setChannelStreamWriterResolver, setFileSystemFactory, setForwarderFactory, setForwardingFilter, setGlobalRequestHandlers, setIoServiceEventListener, setIoServiceFactoryFactory, setNioWorkers, setParentPropertyResolver, setRandomFactory, setReservedSessionMessagesHandler, setScheduledExecutorService, setScheduledExecutorService, setServiceFactories, setSessionDisconnectHandler, setUnknownChannelReferenceHandler, setupSessionTimeout, stopSessionTimeoutListener
getCipherFactories, getCompressionFactories, getDelegate, getKexExtensionHandler, getKeyExchangeFactories, getMacFactories, getSignatureFactories, resolveEffectiveFactories, resolveEffectiveProvider, setCipherFactories, setCompressionFactories, setKexExtensionHandler, setKeyExchangeFactories, setMacFactories, setSignatureFactories
doCloseGracefully, doCloseImmediately
addCloseFutureListener, builder, close, getFutureLock, isClosed, isClosing, preClose, removeCloseFutureListener
debug, debug, debug, debug, debug, error, error, error, error, error, getSimplifiedLogger, info, info, warn, warn, warn, warn, warn, warn, warn, warn
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
getAgentFactory, getAgentForwardingFilter, getChannelFactories, getFileSystemFactory, getForwarderFactory, getForwardingFilter, getGlobalRequestHandlers, getIoServiceFactory, getRandomFactory, getScheduledExecutorService, getServiceFactories, getTcpForwardingFilter, getVersion, getX11ForwardingFilter, resolveAttribute, resolveAttribute
getCipherFactories, getCipherFactoriesNameList, getCipherFactoriesNames, getCompressionFactories, getCompressionFactoriesNameList, getCompressionFactoriesNames, getKeyExchangeFactories, getMacFactories, getMacFactoriesNameList, getMacFactoriesNames, setCipherFactories, setCipherFactoriesNameList, setCipherFactoriesNames, setCipherFactoriesNames, setCompressionFactories, setCompressionFactoriesNameList, setCompressionFactoriesNames, setCompressionFactoriesNames, setKeyExchangeFactories, setMacFactories, setMacFactoriesNameList, setMacFactoriesNames, setMacFactoriesNames
getSignatureFactories, resolveSignatureFactories, setSignatureFactories, setSignatureFactoriesNameList, setSignatureFactoriesNames, setSignatureFactoriesNames
getSignatureFactories, getSignatureFactoriesNameList, getSignatureFactoriesNames
getKexExtensionHandler, setKexExtensionHandler
addSessionListener, getSessionListenerProxy, removeSessionListener
getReservedSessionMessagesHandler, setReservedSessionMessagesHandler
getSessionDisconnectHandler, setSessionDisconnectHandler
addChannelListener, getChannelListenerProxy, removeChannelListener
getChannelStreamWriterResolver, resolveChannelStreamWriter, resolveChannelStreamWriterResolver, setChannelStreamWriterResolver
getUnknownChannelReferenceHandler, resolveUnknownChannelReferenceHandler, setUnknownChannelReferenceHandler
addPortForwardingEventListener, getPortForwardingEventListenerProxy, removePortForwardingEventListener
getIoServiceEventListener, setIoServiceEventListener
clearAttributes, computeAttributeIfAbsent, removeAttribute, setAttribute
attributeKeys, getAttribute, getAttributesCount, ofAttributesMap, ofKeyValuePair
disableSessionHeartbeat, getSessionHeartbeatInterval, getSessionHeartbeatType, setSessionHeartbeat, setSessionHeartbeat
getBoolean, getBooleanProperty, getCharset, getInteger, getIntProperty, getLong, getLongProperty, getObject, getParentPropertyResolver, getProperties, getString, getStringProperty, isEmpty, isEmpty
connect, connect, connect, connect, connect, connect, connect, connect, connect
providerHolderOf
loaderHolderOf
setUserAuthFactoriesNames
getUserAuthFactoriesNameList, getUserAuthFactoriesNames, setUserAuthFactoriesNameList, setUserAuthFactoriesNames
addCloseFutureListener, close, close, close, getMaxCloseWaitTime, isClosed, isClosing, isOpen, removeCloseFutureListener
public static final List<UserAuthFactory> DEFAULT_USER_AUTH_FACTORIES
public static final List<ServiceFactory> DEFAULT_SERVICE_FACTORIES
protected IoConnector connector
protected SessionFactory sessionFactory
protected List<UserAuthFactory> userAuthFactories
public SessionFactory getSessionFactory()
public void setSessionFactory(SessionFactory sessionFactory)
public ClientProxyConnector getClientProxyConnector()
getClientProxyConnector
in interface ClientProxyConnectorHolder
public void setClientProxyConnector(ClientProxyConnector proxyConnector)
setClientProxyConnector
in interface ClientProxyConnectorHolder
public ServerKeyVerifier getServerKeyVerifier()
ClientAuthenticationManager
getServerKeyVerifier
in interface ClientAuthenticationManager
ServerKeyVerifier
to use - never null
public void setServerKeyVerifier(ServerKeyVerifier serverKeyVerifier)
setServerKeyVerifier
in interface ClientAuthenticationManager
public HostConfigEntryResolver getHostConfigEntryResolver()
getHostConfigEntryResolver
in interface ClientFactoryManager
HostConfigEntryResolver
to use in order to resolve the effective session parameters - never
null
public void setHostConfigEntryResolver(HostConfigEntryResolver resolver)
setHostConfigEntryResolver
in interface ClientFactoryManager
public FilePasswordProvider getFilePasswordProvider()
getFilePasswordProvider
in interface FilePasswordProviderHolder
FilePasswordProvider
to use if need to load encrypted identities keys - never null
FilePasswordProvider.EMPTY
public void setFilePasswordProvider(FilePasswordProvider provider)
setFilePasswordProvider
in interface FilePasswordProviderManager
public ClientIdentityLoader getClientIdentityLoader()
getClientIdentityLoader
in interface ClientIdentityLoaderHolder
ClientIdentityLoader
to use in order to load client key pair identities - never null
public void setClientIdentityLoader(ClientIdentityLoader loader)
setClientIdentityLoader
in interface ClientIdentityLoaderManager
public UserInteraction getUserInteraction()
getUserInteraction
in interface ClientAuthenticationManager
UserInteraction
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 ClientAuthenticationManager
public PasswordAuthenticationReporter getPasswordAuthenticationReporter()
getPasswordAuthenticationReporter
in interface ClientAuthenticationManager
public void setPasswordAuthenticationReporter(PasswordAuthenticationReporter reporter)
setPasswordAuthenticationReporter
in interface ClientAuthenticationManager
public HostBasedAuthenticationReporter getHostBasedAuthenticationReporter()
getHostBasedAuthenticationReporter
in interface ClientAuthenticationManager
public void setHostBasedAuthenticationReporter(HostBasedAuthenticationReporter reporter)
setHostBasedAuthenticationReporter
in interface ClientAuthenticationManager
public List<UserAuthFactory> getUserAuthFactories()
UserAuthFactoriesManager
UserAuth
objects.getUserAuthFactories
in interface UserAuthFactoriesManager<ClientSession,UserAuth,UserAuthFactory>
UserAuth
factories, never null
/emptypublic void setUserAuthFactories(List<UserAuthFactory> userAuthFactories)
setUserAuthFactories
in interface UserAuthFactoriesManager<ClientSession,UserAuth,UserAuthFactory>
public AuthenticationIdentitiesProvider getRegisteredIdentities()
getRegisteredIdentities
in interface ClientAuthenticationManager
AuthenticationIdentitiesProvider
to be used for attempting password or public key
authenticationpublic PasswordIdentityProvider getPasswordIdentityProvider()
ClientAuthenticationManager
PasswordIdentityProvider
used to provide password candidatesgetPasswordIdentityProvider
in interface ClientAuthenticationManager
PasswordIdentityProvider
instance - ignored if null
(i.e., no passwords available).ClientAuthenticationManager.addPasswordIdentity(String)
public void setPasswordIdentityProvider(PasswordIdentityProvider provider)
setPasswordIdentityProvider
in interface ClientAuthenticationManager
public void addPasswordIdentity(String password)
addPasswordIdentity
in interface ClientAuthenticationManager
password
- 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 ClientAuthenticationManager
password
- The password to remove - ignored if null
/emptyClientAuthenticationManager.addPasswordIdentity(String)
- or
null
if no match foundpublic void addPublicKeyIdentity(KeyPair kp)
addPublicKeyIdentity
in interface ClientAuthenticationManager
kp
- 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 ClientAuthenticationManager
kp
- The KeyPair
to remove - ignored if null
KeyPair
- same one that was added via ClientAuthenticationManager.addPublicKeyIdentity(KeyPair)
- or
null
if no match foundpublic KeyIdentityProvider getKeyIdentityProvider()
getKeyIdentityProvider
in interface KeyIdentityProviderHolder
KeyIdentityProvider
used to provide key-pair(s) for public key authenticationpublic void setKeyIdentityProvider(KeyIdentityProvider keyIdentityProvider)
setKeyIdentityProvider
in interface KeyIdentityProviderHolder
public PublicKeyAuthenticationReporter getPublicKeyAuthenticationReporter()
getPublicKeyAuthenticationReporter
in interface ClientAuthenticationManager
public void setPublicKeyAuthenticationReporter(PublicKeyAuthenticationReporter reporter)
setPublicKeyAuthenticationReporter
in interface ClientAuthenticationManager
protected void checkConfig()
checkConfig
in class AbstractFactoryManager
public boolean isStarted()
public void start()
started
.public void stop()
public void open() throws IOException
IOException
protected Closeable getInnerCloseable()
getInnerCloseable
in class AbstractInnerCloseable
public ConnectFuture connect(String uriStr) throws IOException
ClientSessionCreator
HostConfigEntry
and connects to itconnect
in interface ClientSessionCreator
uriStr
- The server uri to connect toConnectFuture
IOException
- If failed to resolve the effective target or connect to itClientSessionCreator.connect(HostConfigEntry)
public ConnectFuture connect(String username, SocketAddress targetAddress, AttributeRepository context, SocketAddress localAddress) throws IOException
ClientSessionCreator
HostConfigEntry
and connects to itconnect
in interface ClientSessionCreator
username
- The intended usernametargetAddress
- The intended target SocketAddress
- never null
. If this is an
InetSocketAddress
then the effective HostConfigEntry
is
resolved and used.context
- An optional "context" to be attached to the established session if successfully
connectedlocalAddress
- The local address to use - if null
an automatic ephemeral port and bind address is
usedConnectFuture
IOException
- If failed to resolve the effective target or connect to itpublic ConnectFuture connect(String username, String host, int port, AttributeRepository context, SocketAddress localAddress) throws IOException
ClientSessionCreator
HostConfigEntry
and connects to itconnect
in interface ClientSessionCreator
username
- The intended usernamehost
- The target host name/address - never null
/emptyport
- The target portcontext
- An optional "context" to be attached to the established session if successfully
connectedlocalAddress
- The local address to use - if null
an automatic ephemeral port and bind address is
usedConnectFuture
IOException
- If failed to resolve the effective target or connect to itpublic ConnectFuture connect(HostConfigEntry hostConfig, AttributeRepository context, SocketAddress localAddress) throws IOException
connect
in interface ClientSessionCreator
hostConfig
- The effective HostConfigEntry
to connect to - never null
context
- An optional "context" to be attached to the established session if successfully
connectedlocalAddress
- The local address to use - if null
an automatic ephemeral port and bind address is
usedConnectFuture
IOException
- If failed to create the connection futureprotected ConnectFuture doConnect(HostConfigEntry hostConfig, List<HostConfigEntry> jumps, AttributeRepository context, SocketAddress localAddress) throws IOException
IOException
protected ConnectFuture doConnect(String username, SocketAddress targetAddress, AttributeRepository context, SocketAddress localAddress, KeyIdentityProvider identities, HostConfigEntry hostConfig) throws IOException
IOException
protected List<HostConfigEntry> parseProxyJumps(String proxyJump, AttributeRepository context) throws IOException
IOException
protected HostConfigEntry resolveHost(String username, String host, int port, AttributeRepository context, SocketAddress localAddress) throws IOException
IOException
protected KeyIdentityProvider preloadClientIdentities(Collection<? extends NamedResource> locations) throws IOException
IOException
protected SshFutureListener<IoConnectFuture> createConnectCompletionListener(ConnectFuture connectFuture, String username, SocketAddress address, KeyIdentityProvider identities, HostConfigEntry hostConfig)
protected void onConnectOperationComplete(IoSession ioSession, ConnectFuture connectFuture, String username, SocketAddress address, KeyIdentityProvider identities, HostConfigEntry hostConfig) throws IOException, GeneralSecurityException
IOException
GeneralSecurityException
protected void setupDefaultSessionIdentities(ClientSession session, KeyIdentityProvider extraIdentities) throws IOException, GeneralSecurityException
IOException
GeneralSecurityException
protected IoConnector createConnector()
protected SessionFactory createSessionFactory()
public static SimpleClient setUpDefaultSimpleClient()
SimpleClient
SimpleClient
wrapper. Note: when the wrapper is closed the client is also stoppedsetUpDefaultClient()
,
wrapAsSimpleClient(SshClient)
public static SimpleClient wrapAsSimpleClient(SshClient client)
SshClient
instance as a SimpleClient
client
- 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()
SshClient
with default configurationspublic static <C extends SshClient> C setKeyPairProvider(C client, boolean strict, boolean supportedOnly, FilePasswordProvider provider, LinkOption... options) throws IOException, GeneralSecurityException
C
- The generic client classclient
- The SshClient
to updatedstrict
- If true
then files that do not have the required access rights are
excluded from considerationsupportedOnly
- If true
then ignore identities that are not supported internallyprovider
- A FilePasswordProvider
- may be null
if the loaded keys are
guaranteed not to be encrypted. The argument to
FilePasswordProvider#getPassword
is the path of the file whose key is to
be loadedoptions
- The LinkOption
s to apply when checking for existencenull
KeyPairProvider
was generatedIOException
- If failed to access the file systemGeneralSecurityException
- If failed to load the keyssetKeyPairProvider(SshClient, Path, boolean, boolean, FilePasswordProvider,
LinkOption...)
public static <C extends SshClient> C setKeyPairProvider(C client, Path dir, boolean strict, boolean supportedOnly, FilePasswordProvider provider, LinkOption... options) throws IOException, GeneralSecurityException
C
- The generic client classclient
- The SshClient
to updateddir
- The folder to scan for the built-in identitiesstrict
- If true
then files that do not have the required access rights are
excluded from considerationsupportedOnly
- If true
then ignore identities that are not supported internallyprovider
- A FilePasswordProvider
- may be null
if the loaded keys are
guaranteed not to be encrypted. The argument to
FilePasswordProvider#getPassword
is the path of the file whose key is to
be loadedoptions
- The LinkOption
s to apply when checking for existencenull
KeyIdentityProvider
was generatedIOException
- If failed to access the file systemGeneralSecurityException
- If failed to load the keysClientIdentity.loadDefaultKeyPairProvider(Path, boolean, boolean,
FilePasswordProvider, LinkOption...)
Copyright © 2008–2024 The Apache Software Foundation. All rights reserved.