Interface ClientSession
- All Superinterfaces:
AttributeRepository,AttributeStore,AutoCloseable,Channel,ChannelListenerManager,ChannelStreamWriterResolver,ChannelStreamWriterResolverManager,ClientAuthenticationManager,ClientProxyConnectorHolder,Closeable,Closeable,ConnectionEndpointsIndicator,FactoryManagerHolder,KexExtensionHandlerManager,KexFactoryManager,KeyIdentityProviderHolder,MutableUserHolder,PortForwardingEventListenerManager,PortForwardingInformationProvider,PortForwardingManager,PropertyResolver,ReservedSessionMessagesManager,Session,SessionContext,SessionDisconnectHandlerManager,SessionHeartbeatController,SessionListenerManager,SignatureFactoriesHolder,SignatureFactoriesManager,UnknownChannelReferenceHandlerManager,UserAuthFactoriesManager<ClientSession,,UserAuth, UserAuthFactory> UsernameHolder
- All Known Implementing Classes:
AbstractClientSession,ClientSessionImpl
An authenticated session to a given SSH server.
A client session is established using the SshClient. Once the session has been
created, the user has to authenticate using either ClientAuthenticationManager.addPasswordIdentity(String) or
ClientAuthenticationManager.addPublicKeyIdentity(java.security.KeyPair) followed by a call to auth().
From this session, channels can be created using the createChannel(String) method. Multiple channels can be
created on a given session concurrently.
When using the client in an interactive mode, the waitFor(Collection, long) method can be used to listen to
specific events such as the session being established, authenticated or closed.
Closeable.close(boolean) method.-
Nested Class Summary
Nested ClassesNested classes/interfaces inherited from interface org.apache.sshd.common.AttributeRepository
AttributeRepository.AttributeKey<T>Nested classes/interfaces inherited from interface org.apache.sshd.common.session.SessionHeartbeatController
SessionHeartbeatController.HeartbeatType -
Field Summary
FieldsFields inherited from interface org.apache.sshd.common.channel.throttle.ChannelStreamWriterResolver
NONEFields inherited from interface org.apache.sshd.common.PropertyResolver
EMPTYFields inherited from interface org.apache.sshd.common.session.SessionContext
DEFAULT_SSH_VERSION_PREFIX, FALLBACK_SSH_VERSION_PREFIX, MAX_VERSION_LINE_LENGTH -
Method Summary
Modifier and TypeMethodDescriptionauth()Starts the authentication process.createChannel(String type) Create a channel of the given type.createChannel(String type, String subType) Create a channel of the given type and sub-type.createDirectTcpipChannel(SshdSocketAddress local, SshdSocketAddress remote) Create a direct tcp-ip channel which can be used to stream data to a remote port from the server.default DynamicPortForwardingTrackerStarts a dynamic port forwarding and returns a tracker that stops the forwarding when theclose()method is called.createExecChannel(byte[] command, PtyChannelConfigurationHolder ptyConfig, Map<String, ?> env) Create a channel to execute a command using specific PTY settings and/or environment.default ChannelExeccreateExecChannel(String command) Create a channel to execute a command using default PTY settings and environment.createExecChannel(String command, Charset charset, PtyChannelConfigurationHolder ptyConfig, Map<String, ?> env) Create a channel to execute a command using specific PTY settings and/or environment.default ChannelExeccreateExecChannel(String command, PtyChannelConfigurationHolder ptyConfig, Map<String, ?> env) Create a channel to execute a command using specific PTY settings and/or environment.default ExplicitPortForwardingTrackercreateLocalPortForwardingTracker(int localPort, SshdSocketAddress remote) Starts a local port forwarding and returns a tracker that stops the forwarding when theclose()method is called.default ExplicitPortForwardingTrackercreateLocalPortForwardingTracker(SshdSocketAddress local, SshdSocketAddress remote) Starts a local port forwarding and returns a tracker that stops the forwarding when theclose()method is called.default ExplicitPortForwardingTrackercreateRemotePortForwardingTracker(SshdSocketAddress remote, SshdSocketAddress local) Starts a remote port forwarding and returns a tracker that stops the forwarding when theclose()method is called.default ChannelShellCreate a channel to start a shell using default PTY settings and environment.createShellChannel(PtyChannelConfigurationHolder ptyConfig, Map<String, ?> env) Create a channel to start a shell using specific PTY settings and/or environment.createSubsystemChannel(String subsystem) Create a subsystem channel.default StringexecuteRemoteCommand(String command) Execute a command that requires no input and returns its outputdefault voidexecuteRemoteCommand(String command, OutputStream stdout, OutputStream stderr, Charset charset) Execute a command that requires no input and redirects its STDOUT/STDERR streams to the user-provided onesdefault StringexecuteRemoteCommand(String command, OutputStream stderr, Charset charset) Execute a command that requires no input and returns its outputReturns the original address (after having been translated through host configuration entries if any) that was request to connect.Access to the metadata.Retrieves the server's keypasswordIteratorOf(ClientSession session) Creates a "unified"Iteratorof passwords out of the registered passwords and the extra available ones as a single iterator of passwordsstatic KeyIdentityProviderproviderOf(ClientSession session) Creates a "unified"KeyIdentityProviderof key pairs out of the registeredKeyPairidentities and the extra available ones as a single iterator of key pairsSwitch to a none cipher for performance.waitFor(Collection<ClientSession.ClientSessionEvent> mask, long timeout) Wait for any one of a specific state to be signaled.default Set<ClientSession.ClientSessionEvent> waitFor(Collection<ClientSession.ClientSessionEvent> mask, Duration timeout) Wait for any one of a specific state to be signaled.Methods inherited from interface org.apache.sshd.common.AttributeRepository
attributeKeys, getAttribute, getAttributesCountMethods inherited from interface org.apache.sshd.common.AttributeStore
clearAttributes, computeAttributeIfAbsent, removeAttribute, setAttributeMethods inherited from interface org.apache.sshd.common.channel.ChannelListenerManager
addChannelListener, getChannelListenerProxy, removeChannelListenerMethods inherited from interface org.apache.sshd.common.channel.throttle.ChannelStreamWriterResolverManager
getChannelStreamWriterResolver, resolveChannelStreamWriter, resolveChannelStreamWriterResolver, setChannelStreamWriterResolverMethods inherited from interface org.apache.sshd.client.ClientAuthenticationManager
addPasswordIdentity, addPublicKeyIdentity, getHostBasedAuthenticationReporter, getPasswordAuthenticationReporter, getPasswordIdentityProvider, getPublicKeyAuthenticationReporter, getRegisteredIdentities, getServerKeyVerifier, getUserInteraction, removePasswordIdentity, removePublicKeyIdentity, setHostBasedAuthenticationReporter, setPasswordAuthenticationReporter, setPasswordIdentityProvider, setPublicKeyAuthenticationReporter, setServerKeyVerifier, setUserAuthFactoriesNames, setUserInteractionMethods inherited from interface org.apache.sshd.client.session.ClientProxyConnectorHolder
getClientProxyConnector, setClientProxyConnectorMethods inherited from interface org.apache.sshd.common.Closeable
addCloseFutureListener, close, close, isClosed, isClosing, isOpen, removeCloseFutureListenerMethods inherited from interface org.apache.sshd.common.kex.extension.KexExtensionHandlerManager
getKexExtensionHandler, setKexExtensionHandlerMethods inherited from interface org.apache.sshd.common.kex.KexFactoryManager
getCipherFactories, getCipherFactoriesNameList, getCipherFactoriesNames, getCompressionFactories, getCompressionFactoriesNameList, getCompressionFactoriesNames, getKeyExchangeFactories, getMacFactories, getMacFactoriesNameList, getMacFactoriesNames, setCipherFactories, setCipherFactoriesNameList, setCipherFactoriesNames, setCipherFactoriesNames, setCompressionFactories, setCompressionFactoriesNameList, setCompressionFactoriesNames, setCompressionFactoriesNames, setKeyExchangeFactories, setMacFactories, setMacFactoriesNameList, setMacFactoriesNames, setMacFactoriesNamesMethods inherited from interface org.apache.sshd.common.keyprovider.KeyIdentityProviderHolder
getKeyIdentityProvider, setKeyIdentityProviderMethods inherited from interface org.apache.sshd.common.auth.MutableUserHolder
setUsernameMethods inherited from interface org.apache.sshd.common.forward.PortForwardingEventListenerManager
addPortForwardingEventListener, getPortForwardingEventListenerProxy, removePortForwardingEventListenerMethods inherited from interface org.apache.sshd.common.forward.PortForwardingInformationProvider
getBoundLocalPortForwards, getBoundRemotePortForward, getLocalForwardsBindings, getRemoteForwardsBindings, getStartedLocalPortForwards, getStartedRemotePortForwards, isLocalPortForwardingStartedForPort, isRemotePortForwardingStartedForPortMethods inherited from interface org.apache.sshd.common.forward.PortForwardingManager
startDynamicPortForwarding, startLocalPortForwarding, startLocalPortForwarding, startRemotePortForwarding, stopDynamicPortForwarding, stopLocalPortForwarding, stopRemotePortForwardingMethods inherited from interface org.apache.sshd.common.PropertyResolver
getBoolean, getBooleanProperty, getCharset, getInteger, getIntProperty, getLong, getLongProperty, getObject, getParentPropertyResolver, getProperties, getString, getStringProperty, isEmptyMethods inherited from interface org.apache.sshd.common.session.ReservedSessionMessagesManager
getReservedSessionMessagesHandler, setReservedSessionMessagesHandlerMethods inherited from interface org.apache.sshd.common.session.Session
createBuffer, createBuffer, disconnect, exceptionCaught, getAuthTimeout, getAuthTimeoutStart, getIdleTimeout, getIdleTimeoutStart, getIoSession, getKex, getLocalAddress, getRemoteAddress, getService, getTimeoutStatus, prepareBuffer, reExchangeKeys, request, request, request, request, resetAuthTimeout, resetIdleTimeout, resolveAttribute, sendDebugMessage, sendIgnoreMessage, setAuthenticated, startService, writePacket, writePacket, writePacket, writePacketMethods inherited from interface org.apache.sshd.common.session.SessionContext
getCipherInformation, getClientKexProposals, getClientVersion, getCompressionInformation, getKexNegotiationResult, getKexState, getMacInformation, getNegotiatedKexParameter, getServerKexProposals, getServerVersion, getSessionId, isAuthenticated, isServerSessionMethods inherited from interface org.apache.sshd.common.session.SessionDisconnectHandlerManager
getSessionDisconnectHandler, setSessionDisconnectHandlerMethods inherited from interface org.apache.sshd.common.session.SessionHeartbeatController
disableSessionHeartbeat, getSessionHeartbeatInterval, getSessionHeartbeatType, setSessionHeartbeat, setSessionHeartbeatMethods inherited from interface org.apache.sshd.common.session.SessionListenerManager
addSessionListener, getSessionListenerProxy, removeSessionListenerMethods inherited from interface org.apache.sshd.common.signature.SignatureFactoriesHolder
getSignatureFactories, getSignatureFactoriesNameList, getSignatureFactoriesNamesMethods inherited from interface org.apache.sshd.common.signature.SignatureFactoriesManager
setSignatureFactories, setSignatureFactoriesNameList, setSignatureFactoriesNames, setSignatureFactoriesNamesMethods inherited from interface org.apache.sshd.common.session.UnknownChannelReferenceHandlerManager
getUnknownChannelReferenceHandler, resolveUnknownChannelReferenceHandler, setUnknownChannelReferenceHandlerMethods inherited from interface org.apache.sshd.common.auth.UserAuthFactoriesManager
getUserAuthFactories, getUserAuthFactoriesNameList, getUserAuthFactoriesNames, setUserAuthFactories, setUserAuthFactoriesNameList, setUserAuthFactoriesNamesMethods inherited from interface org.apache.sshd.common.auth.UsernameHolder
getUsername
-
Field Details
-
REMOTE_COMMAND_WAIT_EVENTS
-
-
Method Details
-
getConnectAddress
SocketAddress getConnectAddress()Returns the original address (after having been translated through host configuration entries if any) that was request to connect. It contains the original host or address string that was used. Note: this may be different than the result of theSession.getIoSession()report of the remote peer- Returns:
- The original requested address
-
getConnectionContext
AttributeRepository getConnectionContext()- Returns:
- The "context" data provided when session connection was established -
nullif none.
-
auth
Starts the authentication process. User identities will be tried until the server successfully authenticate the user. User identities must be provided before calling this method usingClientAuthenticationManager.addPasswordIdentity(String)orClientAuthenticationManager.addPublicKeyIdentity(java.security.KeyPair).- Returns:
- the authentication future
- Throws:
IOException- if failed to generate the future- See Also:
-
getServerKey
PublicKey getServerKey()Retrieves the server's key- Returns:
- The server's
PublicKey-nullif KEX not started or not completed
-
createChannel
Create a channel of the given type. Same as callingcreateChannel(type, null).- Parameters:
type- The channel type- Returns:
- The created
ClientChannel - Throws:
IOException- If failed to create the requested channel
-
createChannel
Create a channel of the given type and sub-type.- Parameters:
type- The channel typesubType- The channel sub-type- Returns:
- The created
ClientChannel - Throws:
IOException- If failed to create the requested channel
-
createShellChannel
Create a channel to start a shell using default PTY settings and environment.- Returns:
- The created
ChannelShell - Throws:
IOException- If failed to create the requested channel
-
createShellChannel
ChannelShell createShellChannel(PtyChannelConfigurationHolder ptyConfig, Map<String, ?> env) throws IOExceptionCreate a channel to start a shell using specific PTY settings and/or environment.- Parameters:
ptyConfig- The PTY configuration to use - ifnullthen internal defaults are usedenv- Extra environment configuration to be transmitted to the server - ignored ifnull/empty.- Returns:
- The created
ChannelShell - Throws:
IOException- If failed to create the requested channel
-
createExecChannel
Create a channel to execute a command using default PTY settings and environment.- Parameters:
command- The command to execute- Returns:
- The created
ChannelExec - Throws:
IOException- If failed to create the requested channel
-
createExecChannel
default ChannelExec createExecChannel(String command, PtyChannelConfigurationHolder ptyConfig, Map<String, ?> env) throws IOExceptionCreate a channel to execute a command using specific PTY settings and/or environment.- Parameters:
command- The command to executeptyConfig- The PTY configuration to use - ifnullthen internal defaults are usedenv- Extra environment configuration to be transmitted to the server - ignored ifnull/empty.- Returns:
- The created
ChannelExec - Throws:
IOException- If failed to create the requested channel
-
createExecChannel
ChannelExec createExecChannel(String command, Charset charset, PtyChannelConfigurationHolder ptyConfig, Map<String, ?> env) throws IOExceptionCreate a channel to execute a command using specific PTY settings and/or environment.- Parameters:
command- The command to executecharset- TheCharsetto use for sending the command stringptyConfig- The PTY configuration to use - ifnullthen internal defaults are usedenv- Extra environment configuration to be transmitted to the server - ignored ifnull/empty.- Returns:
- The created
ChannelExec - Throws:
IOException- If failed to create the requested channel
-
createExecChannel
ChannelExec createExecChannel(byte[] command, PtyChannelConfigurationHolder ptyConfig, Map<String, ?> env) throws IOExceptionCreate a channel to execute a command using specific PTY settings and/or environment.- Parameters:
command- The command to executeptyConfig- The PTY configuration to use - ifnullthen internal defaults are usedenv- Extra environment configuration to be transmitted to the server - ignored ifnull/empty.- Returns:
- The created
ChannelExec - Throws:
IOException- If failed to create the requested channel
-
executeRemoteCommand
Execute a command that requires no input and returns its output- Parameters:
command- The command to execute- Returns:
- The command's standard output result (assumed to be in US-ASCII)
- Throws:
IOException- If failed to execute the command - including if anything was written to the standard error or a non-zero exit status was received. If this happens, then aRemoteExceptionis thrown with a cause ofServerExceptioncontaining the remote captured standard error - including CR/LF(s)- See Also:
-
executeRemoteCommand
default String executeRemoteCommand(String command, OutputStream stderr, Charset charset) throws IOException Execute a command that requires no input and returns its output- Parameters:
command- The command to execute - without a terminating LFstderr- Standard error output stream - ifnullthen error stream data is ignored. Note: if the stream is notnullthen it will be left open when this method returns or exception is throwncharset- The commandCharsetfor input/output/error - ifnullthen US_ASCII is assumed- Returns:
- The command's standard output result
- Throws:
IOException- If failed to manage the command channel - Note: the code does not check if anything was output to the standard error stream, but does check the reported exit status (if any) for non-zero value. If non-zero exit status received then aRemoteExceptionis thrown with' aServerExceptioncause containing the exits value- See Also:
-
executeRemoteCommand
default void executeRemoteCommand(String command, OutputStream stdout, OutputStream stderr, Charset charset) throws IOException Execute a command that requires no input and redirects its STDOUT/STDERR streams to the user-provided ones- Parameters:
command- The command to execute - without a terminating LFstdout- Standard output stream - ifnullthen stream data is ignored. Note: if the stream is notnullthen it will be left open when this method returns or exception is thrownstderr- Error output stream - ifnullthen stream data is ignored. Note: if the stream is notnullthen it will be left open when this method returns or exception is throwncharset- The commandCharsetfor output/error - ifnullthen US_ASCII is assumed- Throws:
IOException- If failed to execute the command or got a non-zero exit status- See Also:
-
createSubsystemChannel
Create a subsystem channel.- Parameters:
subsystem- The subsystem name- Returns:
- The created
ChannelSubsystem - Throws:
IOException- If failed to create the requested channel
-
createDirectTcpipChannel
ChannelDirectTcpip createDirectTcpipChannel(SshdSocketAddress local, SshdSocketAddress remote) throws IOException Create a direct tcp-ip channel which can be used to stream data to a remote port from the server.- Parameters:
local- The local addressremote- The remote address- Returns:
- The created
ChannelDirectTcpip - Throws:
IOException- If failed to create the requested channel
-
createLocalPortForwardingTracker
default ExplicitPortForwardingTracker createLocalPortForwardingTracker(int localPort, SshdSocketAddress remote) throws IOException Starts a local port forwarding and returns a tracker that stops the forwarding when theclose()method is called. This tracker can be used in atry-with-resourceblock to ensure cleanup of the set up forwarding.- Parameters:
localPort- The local port - if zero one is allocatedremote- The remote address- Returns:
- The tracker instance
- Throws:
IOException- If failed to set up the requested forwarding- See Also:
-
createLocalPortForwardingTracker
default ExplicitPortForwardingTracker createLocalPortForwardingTracker(SshdSocketAddress local, SshdSocketAddress remote) throws IOException Starts a local port forwarding and returns a tracker that stops the forwarding when theclose()method is called. This tracker can be used in atry-with-resourceblock to ensure cleanup of the set up forwarding.- Parameters:
local- The local addressremote- The remote address- Returns:
- The tracker instance
- Throws:
IOException- If failed to set up the requested forwarding- See Also:
-
createRemotePortForwardingTracker
default ExplicitPortForwardingTracker createRemotePortForwardingTracker(SshdSocketAddress remote, SshdSocketAddress local) throws IOException Starts a remote port forwarding and returns a tracker that stops the forwarding when theclose()method is called. This tracker can be used in atry-with-resourceblock to ensure cleanup of the set up forwarding.- Parameters:
remote- The remote addresslocal- The local address- Returns:
- The tracker instance
- Throws:
IOException- If failed to set up the requested forwarding- See Also:
-
createDynamicPortForwardingTracker
default DynamicPortForwardingTracker createDynamicPortForwardingTracker(SshdSocketAddress local) throws IOException Starts a dynamic port forwarding and returns a tracker that stops the forwarding when theclose()method is called. This tracker can be used in atry-with-resourceblock to ensure cleanup of the set up forwarding.- Parameters:
local- The local address- Returns:
- The tracker instance
- Throws:
IOException- If failed to set up the requested forwarding- See Also:
-
getSessionState
Set<ClientSession.ClientSessionEvent> getSessionState()- Returns:
- A snapshot of the current session state
- See Also:
-
waitFor
Set<ClientSession.ClientSessionEvent> waitFor(Collection<ClientSession.ClientSessionEvent> mask, long timeout) Wait for any one of a specific state to be signaled.- Parameters:
mask- The requestClientSession.ClientSessionEvents masktimeout- Wait time in milliseconds - non-positive means forever- Returns:
- The actual state that was detected either due to the mask yielding one of the states or due to
timeout (in which case the
ClientSession.ClientSessionEvent.TIMEOUTvalue is set)
-
waitFor
default Set<ClientSession.ClientSessionEvent> waitFor(Collection<ClientSession.ClientSessionEvent> mask, Duration timeout) Wait for any one of a specific state to be signaled.- Parameters:
mask- The requestClientSession.ClientSessionEvents masktimeout- Wait time - null means forever- Returns:
- The actual state that was detected either due to the mask yielding one of the states or due to
timeout (in which case the
ClientSession.ClientSessionEvent.TIMEOUTvalue is set)
-
getMetadataMap
Access to the metadata.- Returns:
- The metadata
Map- Note: access to the map is notsynchronizedin any way - up to the user to take care of mutual exclusion if necessary
-
getFactoryManager
ClientFactoryManager getFactoryManager()- Specified by:
getFactoryManagerin interfaceFactoryManagerHolder- Returns:
- The ClientFactoryManager for this session.
-
switchToNoneCipher
Switch to a none cipher for performance.
This should be done after the authentication phase has been performed. After such a switch, interactive channels are not allowed anymore. Both client and server must have been configured to support the none cipher. If that's not the case, the returned future will be set with an exception.
- Returns:
- an
KeyExchangeFuturethat can be used to wait for the exchange to be finished - Throws:
IOException- if a key exchange is already running
-
providerOf
Creates a "unified"KeyIdentityProviderof key pairs out of the registeredKeyPairidentities and the extra available ones as a single iterator of key pairs- Parameters:
session- TheClientSession- ignored ifnull(i.e., empty iterator returned)- Returns:
- The wrapping KeyIdentityProvider
- See Also:
-
passwordIteratorOf
static Iterator<String> passwordIteratorOf(ClientSession session) throws IOException, GeneralSecurityException Creates a "unified"Iteratorof passwords out of the registered passwords and the extra available ones as a single iterator of passwords- Parameters:
session- TheClientSession- ignored ifnull(i.e., empty iterator returned)- Returns:
- The wrapping iterator
- Throws:
IOException- If failed to load the passwordsGeneralSecurityException- If some security issue with the passwords- See Also:
-