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.State
AttributeStore.AttributeKey<T>
Modifier and Type | Field and Description |
---|---|
private ClientIdentityLoader |
clientIdentityLoader |
protected IoConnector |
connector |
static java.util.List<ServiceFactory> |
DEFAULT_SERVICE_FACTORIES |
static Factory<SshClient> |
DEFAULT_SSH_CLIENT_FACTORY |
static java.util.List<NamedFactory<UserAuth>> |
DEFAULT_USER_AUTH_FACTORIES
Default user authentication preferences if not set
|
private FilePasswordProvider |
filePasswordProvider |
private HostConfigEntryResolver |
hostConfigEntryResolver |
private java.util.List<java.lang.Object> |
identities |
private AuthenticationIdentitiesProvider |
identitiesProvider |
private PasswordIdentityProvider |
passwordIdentityProvider |
private ClientProxyConnector |
proxyConnector |
private ServerKeyVerifier |
serverKeyVerifier |
protected SessionFactory |
sessionFactory |
private java.util.concurrent.atomic.AtomicBoolean |
started |
protected java.util.List<NamedFactory<UserAuth>> |
userAuthFactories |
protected UserInteraction |
userInteraction |
agentFactory, channelFactories, channelListenerProxy, channelListeners, executor, fileSystemFactory, forwarderFactory, forwardingFilter, globalRequestHandlers, ioServiceFactory, ioServiceFactoryFactory, randomFactory, serviceFactories, sessionListenerProxy, sessionListeners, sessionTimeoutListener, shutdownExecutor, timeoutListenerFuture, tunnelListenerProxy, tunnelListeners
closeFuture, lock, state
log
CLIENT_IDENTIFICATION, DEFAULT_HEARTBEAT_INTERVAL, DEFAULT_IGNORE_INVALID_IDENTITIES, DEFAULT_KEEP_ALIVE_HEARTBEAT_STRING, HEARTBEAT_INTERVAL, HEARTBEAT_REQUEST, IGNORE_INVALID_IDENTITIES
AGENT_FORWARDING_TYPE, AGENT_FORWARDING_TYPE_IETF, AGENT_FORWARDING_TYPE_OPENSSH, AUTH_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_TIMEOUT
NONE
EMPTY
DEFAULT_PASSWORD_PROMPTS, PASSWORD_PROMPTS, PREFERRED_AUTHS
CLOSE_WAIT_TIMEOUT, DEFAULT_CLOSE_WAIT_TIMEOUT
Constructor and Description |
---|
SshClient() |
Modifier and Type | Method and Description |
---|---|
void |
addPasswordIdentity(java.lang.String password) |
void |
addPublicKeyIdentity(java.security.KeyPair kp) |
protected void |
checkConfig() |
ConnectFuture |
connect(HostConfigEntry hostConfig) |
ConnectFuture |
connect(java.lang.String username,
java.net.SocketAddress address)
Resolves the effective
HostConfigEntry and connects to it |
ConnectFuture |
connect(java.lang.String username,
java.lang.String host,
int port)
Resolves the effective
HostConfigEntry and connects to it |
protected SshFutureListener<IoConnectFuture> |
createConnectCompletionListener(ConnectFuture connectFuture,
java.lang.String username,
java.net.SocketAddress address,
java.util.Collection<? extends java.security.KeyPair> identities,
boolean useDefaultIdentities) |
protected IoConnector |
createConnector() |
protected SessionFactory |
createSessionFactory() |
protected ConnectFuture |
doConnect(java.lang.String username,
java.net.SocketAddress address,
java.util.Collection<? extends java.security.KeyPair> identities,
boolean useDefaultIdentities) |
ClientIdentityLoader |
getClientIdentityLoader() |
ClientProxyConnector |
getClientProxyConnector() |
FilePasswordProvider |
getFilePasswordProvider() |
HostConfigEntryResolver |
getHostConfigEntryResolver() |
protected Closeable |
getInnerCloseable() |
PasswordIdentityProvider |
getPasswordIdentityProvider()
Retrieve
PasswordIdentityProvider used to provide password
candidates |
AuthenticationIdentitiesProvider |
getRegisteredIdentities() |
ServerKeyVerifier |
getServerKeyVerifier()
Retrieve the server key verifier to be used to check the key when connecting
to an SSH server.
|
SessionFactory |
getSessionFactory() |
java.util.List<NamedFactory<UserAuth>> |
getUserAuthFactories() |
UserInteraction |
getUserInteraction() |
boolean |
isStarted() |
protected java.util.List<java.security.KeyPair> |
loadClientIdentities(java.util.Collection<java.lang.String> locations,
java.nio.file.LinkOption... options) |
protected void |
onConnectOperationComplete(IoSession ioSession,
ConnectFuture connectFuture,
java.lang.String username,
java.net.SocketAddress address,
java.util.Collection<? extends java.security.KeyPair> identities,
boolean useDefaultIdentities) |
void |
open() |
java.lang.String |
removePasswordIdentity(java.lang.String password) |
java.security.KeyPair |
removePublicKeyIdentity(java.security.KeyPair kp) |
void |
setClientIdentityLoader(ClientIdentityLoader loader) |
void |
setClientProxyConnector(ClientProxyConnector proxyConnector) |
void |
setFilePasswordProvider(FilePasswordProvider provider) |
void |
setHostConfigEntryResolver(HostConfigEntryResolver resolver) |
void |
setPasswordIdentityProvider(PasswordIdentityProvider provider) |
void |
setServerKeyVerifier(ServerKeyVerifier serverKeyVerifier) |
void |
setSessionFactory(SessionFactory sessionFactory) |
static SshClient |
setUpDefaultClient()
Setup a default client.
|
protected void |
setupDefaultSessionIdentities(ClientSession session) |
static SimpleClient |
setUpDefaultSimpleClient()
Setup a default client, starts it and then wraps it as a
SimpleClient |
void |
setUserAuthFactories(java.util.List<NamedFactory<UserAuth>> userAuthFactories) |
void |
setUserInteraction(UserInteraction userInteraction) |
void |
start()
Starts the SSH client and can start creating sessions using it.
|
void |
stop() |
java.lang.String |
toString() |
static SimpleClient |
wrapAsSimpleClient(SshClient client)
Wraps an
SshClient instance as a SimpleClient |
addChannelListener, addPortForwardingEventListener, addSessionListener, createSessionTimeoutListener, getAgentFactory, getAttribute, getChannelFactories, getChannelListenerProxy, getChannelStreamPacketWriterResolver, getFileSystemFactory, getForwarderFactory, getForwardingFilter, getGlobalRequestHandlers, getIoServiceFactory, getIoServiceFactoryFactory, getNioWorkers, getParentPropertyResolver, getPortForwardingEventListenerProxy, getProperties, getRandomFactory, getReservedSessionMessagesHandler, getScheduledExecutorService, getServiceFactories, getSessionListenerProxy, getUnknownChannelReferenceHandler, getVersion, removeAttribute, removeChannelListener, removePortForwardingEventListener, removeSessionListener, removeSessionTimeout, resolveAttribute, resolveUnknownChannelReferenceHandler, setAgentFactory, setAttribute, setChannelFactories, setChannelStreamPacketWriterResolver, setFileSystemFactory, setForwarderFactory, setForwardingFilter, setGlobalRequestHandlers, setIoServiceFactoryFactory, setNioWorkers, setParentPropertyResolver, setRandomFactory, setReservedSessionMessagesHandler, setScheduledExecutorService, setScheduledExecutorService, setServiceFactories, setUnknownChannelReferenceHandler, setupSessionTimeout, stopSessionTimeoutListener
getCipherFactories, getCompressionFactories, getKeyExchangeFactories, getKeyPairProvider, getMacFactories, getSignatureFactories, resolveEffectiveFactories, resolveEffectiveProvider, setCipherFactories, setCompressionFactories, setKeyExchangeFactories, setKeyPairProvider, setMacFactories, setSignatureFactories
doCloseGracefully, doCloseImmediately
addCloseFutureListener, builder, close, isClosed, isClosing, preClose, removeCloseFutureListener
getSimplifiedLogger
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
getAgentFactory, getAgentForwardingFilter, getChannelFactories, getFileSystemFactory, getForwarderFactory, getForwardingFilter, getGlobalRequestHandlers, getIoServiceFactory, getRandomFactory, getScheduledExecutorService, getServiceFactories, getTcpForwardingFilter, getVersion, getX11ForwardingFilter
getCipherFactories, getCipherFactoriesNameList, getCipherFactoriesNames, getCompressionFactories, getCompressionFactoriesNameList, getCompressionFactoriesNames, getKeyExchangeFactories, getMacFactories, getMacFactoriesNameList, getMacFactoriesNames, setCipherFactories, setCipherFactoriesNameList, setCipherFactoriesNames, setCipherFactoriesNames, setCompressionFactories, setCompressionFactoriesNameList, setCompressionFactoriesNames, setCompressionFactoriesNames, setKeyExchangeFactories, setMacFactories, setMacFactoriesNameList, setMacFactoriesNames, setMacFactoriesNames
getKeyPairProvider, setKeyPairProvider
getSignatureFactories, getSignatureFactories, getSignatureFactoriesNameList, getSignatureFactoriesNames, resolveSignatureFactories, setSignatureFactories, setSignatureFactoriesNameList, setSignatureFactoriesNames, setSignatureFactoriesNames
addSessionListener, getSessionListenerProxy, removeSessionListener
getReservedSessionMessagesHandler, setReservedSessionMessagesHandler
addChannelListener, getChannelListenerProxy, removeChannelListener
getChannelStreamPacketWriterResolver, resolveChannelStreamPacketWriter, resolveChannelStreamPacketWriterResolver, setChannelStreamPacketWriterResolver
getUnknownChannelReferenceHandler, resolveUnknownChannelReferenceHandler, setUnknownChannelReferenceHandler
addPortForwardingEventListener, getPortForwardingEventListenerProxy, removePortForwardingEventListener
getAttribute, removeAttribute, resolveAttribute, resolveAttribute, resolveAttribute, resolveAttribute, setAttribute
getBoolean, getBooleanProperty, getInteger, getIntProperty, getLong, getLongProperty, getObject, getParentPropertyResolver, getProperties, getString, getStringProperty
getUserAuthFactoriesNameList, getUserAuthFactoriesNames, setUserAuthFactoriesNameList, setUserAuthFactoriesNames, setUserAuthFactoriesNames
addCloseFutureListener, close, close, close, getMaxCloseWaitTime, isClosed, isClosing, isOpen, removeCloseFutureListener
public static final java.util.List<NamedFactory<UserAuth>> DEFAULT_USER_AUTH_FACTORIES
public static final java.util.List<ServiceFactory> DEFAULT_SERVICE_FACTORIES
protected IoConnector connector
protected SessionFactory sessionFactory
protected UserInteraction userInteraction
protected java.util.List<NamedFactory<UserAuth>> userAuthFactories
private ClientProxyConnector proxyConnector
private ServerKeyVerifier serverKeyVerifier
private HostConfigEntryResolver hostConfigEntryResolver
private ClientIdentityLoader clientIdentityLoader
private FilePasswordProvider filePasswordProvider
private PasswordIdentityProvider passwordIdentityProvider
private final java.util.List<java.lang.Object> identities
private final AuthenticationIdentitiesProvider identitiesProvider
private final java.util.concurrent.atomic.AtomicBoolean started
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 ClientFactoryManager
FilePasswordProvider
to use if need to load encrypted
identities keys - never null
FilePasswordProvider.EMPTY
public void setFilePasswordProvider(FilePasswordProvider provider)
setFilePasswordProvider
in interface ClientFactoryManager
public ClientIdentityLoader getClientIdentityLoader()
getClientIdentityLoader
in interface ClientFactoryManager
ClientIdentityLoader
to use in order to load client
key pair identities - never null
public void setClientIdentityLoader(ClientIdentityLoader loader)
setClientIdentityLoader
in interface ClientFactoryManager
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 java.util.List<NamedFactory<UserAuth>> getUserAuthFactories()
getUserAuthFactories
in interface ClientAuthenticationManager
List
of UserAuth
NamedFactory
-ies - never
null
/emptypublic void setUserAuthFactories(java.util.List<NamedFactory<UserAuth>> userAuthFactories)
setUserAuthFactories
in interface ClientAuthenticationManager
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)public void setPasswordIdentityProvider(PasswordIdentityProvider provider)
setPasswordIdentityProvider
in interface ClientAuthenticationManager
public void addPasswordIdentity(java.lang.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 java.lang.String removePasswordIdentity(java.lang.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(java.security.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 java.security.KeyPair removePublicKeyIdentity(java.security.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 foundprotected void checkConfig()
checkConfig
in class AbstractFactoryManager
public boolean isStarted()
public void start()
started
.public void stop()
public void open() throws java.io.IOException
java.io.IOException
protected Closeable getInnerCloseable()
getInnerCloseable
in class AbstractInnerCloseable
public ConnectFuture connect(java.lang.String username, java.lang.String host, int port) throws java.io.IOException
ClientSessionCreator
HostConfigEntry
and connects to itconnect
in interface ClientSessionCreator
username
- The intended usernamehost
- The target host name/address - never null
/emptyport
- The target portConnectFuture
java.io.IOException
- If failed to resolve the effective target or
connect to itClientSessionCreator.connect(HostConfigEntry)
public ConnectFuture connect(java.lang.String username, java.net.SocketAddress address) throws java.io.IOException
ClientSessionCreator
HostConfigEntry
and connects to itconnect
in interface ClientSessionCreator
username
- The intended usernameaddress
- The intended SocketAddress
- never null
. If
this is an InetSocketAddress
then the effective HostConfigEntry
is resolved and used.ConnectFuture
java.io.IOException
- If failed to resolve the effective target or
connect to itClientSessionCreator.connect(HostConfigEntry)
public ConnectFuture connect(HostConfigEntry hostConfig) throws java.io.IOException
connect
in interface ClientSessionCreator
hostConfig
- The effective HostConfigEntry
to connect to - never null
ConnectFuture
java.io.IOException
- If failed to create the connection futureprotected java.util.List<java.security.KeyPair> loadClientIdentities(java.util.Collection<java.lang.String> locations, java.nio.file.LinkOption... options) throws java.io.IOException
java.io.IOException
protected ConnectFuture doConnect(java.lang.String username, java.net.SocketAddress address, java.util.Collection<? extends java.security.KeyPair> identities, boolean useDefaultIdentities) throws java.io.IOException
java.io.IOException
protected SshFutureListener<IoConnectFuture> createConnectCompletionListener(ConnectFuture connectFuture, java.lang.String username, java.net.SocketAddress address, java.util.Collection<? extends java.security.KeyPair> identities, boolean useDefaultIdentities)
protected void onConnectOperationComplete(IoSession ioSession, ConnectFuture connectFuture, java.lang.String username, java.net.SocketAddress address, java.util.Collection<? extends java.security.KeyPair> identities, boolean useDefaultIdentities)
protected void setupDefaultSessionIdentities(ClientSession session)
protected IoConnector createConnector()
protected SessionFactory createSessionFactory()
public java.lang.String toString()
toString
in class java.lang.Object
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()