Class Ssh
- All Implemented Interfaces:
AutoCloseable
Connect to SSH servers, authenticate, run commands, open channels, and manage secure sessions.
Chilkat.Ssh is Chilkat's primary SSH client class for
applications that need secure remote command execution, shell sessions,
channel-based communication, port forwarding, and detailed control over SSH
transport behavior. It supports password and public-key authentication,
keyboard-interactive authentication, stdout and stderr handling, proxies,
host key inspection, algorithm selection, connection reuse, and detailed
diagnostics for authentication, transport, channel, and disconnect issues.
SSH connection setup
Connect to SSH servers with configurable timeouts, host key handling, proxy settings, preferred IP behavior, and detailed connection logging.
Authentication options
Authenticate with passwords, private keys, combined password/key workflows, or keyboard-interactive authentication when required by the server.
Remote commands
Execute commands on the server, read stdout and stderr, inspect exit status, and manage command channels.
Shell sessions
Open interactive shell channels for command-line sessions that require ongoing input and output rather than a single command result.
Port forwarding
Open SSH channels for direct TCP/IP forwarding scenarios, such as connecting securely through an SSH server to another host and port.
Algorithm and diagnostics
Control allowed SSH algorithms and use detailed error text, session information, and logs to troubleshoot negotiation or server behavior.
Common pattern: Connect to the SSH server, authenticate, open a command, shell, or forwarding channel, read the channel output until complete, close the channel, and then disconnect. Use algorithm controls and diagnostics when working with strict servers, legacy systems, or security-policy requirements.
For an extended overview, see Ssh Class Overview.
</section>
Event-capable: long-running methods report progress through a ProgressListener installed
with setProgressListener(ProgressListener), onAbortCheck(BooleanSupplier),
onPercentDone(IntPredicate) or onProgressInfo(BiConsumer).
Instances hold a native Chilkat object: close them with ChilkatObject.close() (try-with-resources) when
done; an unclosed instance is freed when it becomes unreachable.
- See Also:
- Online reference
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoidauthenticatePk(String username, SshKey privateKey)Authenticates an active, unauthenticated SSH connection using public-key authentication.voidauthenticatePw(String login, String password)Authenticates an active, unauthenticated SSH connection usingloginandpassword.voidauthenticatePwPk(String username, String password, SshKey privateKey)Authenticates with a server that requires both a password and a private key.voidauthenticateSecPw(SecureString login, SecureString password)Performs the same authentication as, but receives the login and password inauthenticatePw(String, String)SecureStringobjects.voidauthenticateSecPwPk(SecureString username, SecureString password, SshKey privateKey)Performs the same combined password/private-key authentication as, but receives the username and password inauthenticatePwPk(String, String, SshKey)SecureStringobjects.booleanchannelIsOpen(int channelNum)ReturnstruewhenchannelNumidentifies a channel that Chilkat currently considers open for application I/O; otherwise returnsfalse.intchannelPoll(int channelNum, int pollTimeoutMs)PollschannelNumfor incoming SSH channel messages, waiting at mostpollTimeoutMsmilliseconds.intchannelRead(int channelNum)Reads incoming SSH channel messages forchannelNum.intchannelReadAndPoll(int channelNum, int pollTimeoutMs)ReadschannelNumin two phases: Waits for the first applicable channel message.intchannelReadAndPoll2(int channelNum, int pollTimeoutMs, int maxNumBytes)Works like, but also returns after newly processed data causes the total buffered channel data to reach or exceedchannelReadAndPoll(int, int)maxNumBytes.booleanchannelReceivedClose(int channelNum)Returnstrueif an SSHCLOSEmessage has been received forchannelNum.booleanchannelReceivedEof(int channelNum)Returnstrueif an SSHEOFmessage has been received forchannelNum.booleanchannelReceivedExitStatus(int channelNum)Returnstrueif the server supplied an exit-status value forchannelNum.voidchannelReceiveToClose(int channelNum)Receives data onchannelNumuntil the server sends and Chilkat processes channelCLOSE.voidchannelReceiveUntilMatch(int channelNum, String matchPattern, String charset, boolean caseSensitive)Receives text onchannelNumuntil the accumulated text matchesmatchPattern.voidchannelReceiveUntilMatchN(int channelNum, StringArray matchPatterns, String charset, boolean caseSensitive)Works like, but returns when any pattern inchannelReceiveUntilMatch(int, String, String, boolean)matchPatternsis matched.voidchannelRelease(int channelNum)Releases Chilkat’s retained local resources forchannelNumafter all required output and exit information has been retrieved.voidchannelSendClose(int channelNum)Sends an SSHCLOSEmessage forchannelNumand immediately marks the channel locally closed.voidchannelSendEof(int channelNum)Sends an SSHEOFmessage onchannelNum.voidchannelSendString(int channelNum, String textData, String charset)EncodestextDatausingcharset, then sends the resulting bytes onchannelNum.booleanReturnstruewhen the underlying SSH transport currently appears connected, andfalsewhen the object is unconnected, has been disconnected, a connection attempt failed, or transport loss has already been detected.voidClears all TTY mode settings previously added with.setTtyMode(String, int)voidEstablishes an SSH connection todomainNameon the TCP port specified byport.voidconnectThroughSsh(Ssh ssh, String hostname, int port)Connects to another SSH server through the already connected and authenticatedSshobject inssh.continueKeyboardAuth(String response)Continues keyboard-interactive authentication by submitting the response inresponse.voidCloses the current SSH transport.booleanSet totrueto request that the currently running Chilkat operation abort.intContains the result code from the most recent call to an SSH authentication method, including,authenticatePw(String, String),authenticatePk(String, SshKey), and theirauthenticatePwPk(String, String, SshKey)SecureStringvariants.Queries a connected, unauthenticated SSH server for its advertised user-authentication methods.booleanControls whether recognized caret notation is converted to ASCII control characters in strings passed toandsendReqExec(int, String).channelSendString(int, String, String)intgetChannelExitStatus(int channelNum)Returns the remote process exit status received forchannelNum.intgetChannelNumber(int index)Returns the channel number at zero-based enumerationindexin the active channel collection.intContains the SSH channel-open failure code when the server rejects a request to open a channel.Contains the descriptive text associated withwhen the server rejects a channel-open request.getChannelOpenFailCode()getChannelType(int index)Returns the type of the channel at zero-based enumerationindexin the active channel collection.Specifies the SSH client-identification string sent when a connection is established.This property is normally left unset. Set it only when the computer has multiple network interfaces or multiple local IP addresses and the application needs to use a specific one.intThis property is normally left at its default value of0. In this case, the operating system automatically chooses an unused local port from its ephemeral-port range.intSpecifies the maximum number of milliseconds allowed for the remote endpoint to accept the TCP connection.intContains the reason code from the most recent SSHDISCONNECTmessage received from the server.Contains the descriptive text sent with the most recent server SSHDISCONNECTmessage.booleanControls whether SSH compression may be negotiated.booleanEnables automatic resolution of secret specification strings from secure operating-system storage.Restricts SSH cipher negotiation to one cipher or a comma-separated preference list.intSpecifies the interval, in milliseconds, betweenevent callbacks during operations that support progress events.AbortCheckSpecifies the preferred host-key algorithm used during SSH connection establishment.Contains the connected server’s host-key fingerprint in Chilkat’s legacy MD5 format:getHostKeyFP(String hashAlg, boolean includeKeyType, boolean includeHashName)Returns the active connection’s server host-key fingerprint.Specifies the authentication method used by an HTTP proxy.Specifies the optional Windows domain used for NTLM authentication with an HTTP proxy.Specifies the hostname or numeric IP address of an HTTP proxy.Specifies the password used to authenticate with an HTTP proxy.intSpecifies the HTTP proxy port.Specifies the username used to authenticate with an HTTP proxy.intSpecifies an inactivity interval, in milliseconds, for SSH receive waits that use this property.booleanReturnstruewhen Chilkat currently considers the SSH transport connected.booleanControls whether SSH protocol traffic is accumulated in.getSessionLog()voidgetLastJsonData(JsonObject json)Copies structured diagnostic information from the most recently called method into theJsonObjectinjson.intSpecifies the maximum SSH channel packet size advertised in theSSH_MSG_CHANNEL_OPENmessage.intReturns the number of channel records in the active SSH channel collection.booleanIndicates that the server rejected password authentication because it requires the user to change the password.booleanControls which address family is selected when DNS resolution for a hostname returns both an IPv4 address and an IPv6 address.Returns the installed listener, ornull.intSpecifies a receive timeout, in milliseconds, for SSH methods that use this property.intgetReceivedNumBytes(int channelNum)Returns the number of bytes currently available in the normal receive buffer forchannelNum.voidgetReceivedSb(int channelNum, String charset, StringBuilder sb)Decodes and appends tosball text currently accumulated in the normal receive buffer forchannelNum, usingcharset.getReceivedStderrText(int channelNum, String charset)Decodes and returns all text currently accumulated in the separate stderr buffer forchannelNum, usingcharset.getReceivedText(int channelNum, String charset)Decodes and returns all text currently accumulated in the normal receive buffer forchannelNum, usingcharset.getReceivedTextS(int channelNum, String substr, String charset)Decodes text in the normal receive buffer forchannelNumand performs a literal, case-sensitive search forsubstrusingcharset.Specifies the character encoding used for command text sent by,sendReqExec(int, String), andquickCommand(String, String).quickCmdSend(String)Contains the SSH server-identification string received during connection establishment.Contains the in-memory SSH protocol log for the current or most recently completed successful session.Specifies the SOCKS proxy hostname or IPv4 address.Specifies the SOCKS5 password when username/password authentication is required.intSpecifies the SOCKS proxy port.Specifies the SOCKS username.intSelects whether and how a SOCKS proxy is used.intSpecifies the socket receive-buffer size.intSpecifies the socket send-buffer size.booleanControls whether SSH extended-data received as stderr is merged into the normal channel receive buffer.booleanControls whether terminal control sequences are removed from received text, so that the text returned is plain text.booleanControls theTCP_NODELAYsetting for the underlying TCP connection.Provides comma-separated compatibility and security options for uncommon SSH scenarios.Contains a user-authentication banner received from the server during authentication.voidonAbortCheck(BooleanSupplier callback)Installs a listener whose only callback isabortCheck: called everyHeartbeatMsmilliseconds during a long-running method; returntrueto abort it.voidonPercentDone(IntPredicate callback)Installs a listener whose only callback ispercentDone: called with the completion percentage (0..100) as a long-running method progresses; returntrueto abort it.voidonProgressInfo(BiConsumer<String,String> callback)Installs a listener whose only callback isprogressInfo: called with a name/value pair of progress information as a long-running method proceeds.intopenCustomChannel(String channelType)Requests a custom SSH channel whose application-defined channel type is supplied inchannelType.intopenDirectTcpIpChannel(String targetHostname, int targetPort)Opens adirect-tcpipchannel through the SSH server totargetHostnameandtargetPort.intOpens a new SSH session channel.peekReceivedText(int channelNum, String charset)Returns the text currently buffered in the normal receive buffer forchannelNum, decoded usingcharset, without removing any bytes.intquickCmdCheck(int pollTimeoutMs)Waits up topollTimeoutMsmilliseconds for any command previously started byto complete.quickCmdSend(String)intquickCmdSend(String command)Starts a remote command and immediately returns its channel number, allowing multiple commands to run concurrently on the same authenticated SSH connection.quickCommand(String command, String charset)Executes one noninteractive remote command and returns the stdout collected as text.intStarts a remote shell using the simplified sequenceOpenSessionChannel→SendReqPty→SendReqShell.voidreKey()Initiates SSH key re-exchange and waits for it to complete.voidSends an SSHIGNOREmessage.voidsendReqExec(int channelNum, String commandLine)Requests execution ofcommandLineon the session channel identified bychannelNum.voidsendReqPty(int channelNum, String termType, int widthInChars, int heightInChars, int widthInPixels, int heightInPixels)Recommendation for automation: Do not request a pseudo-terminal unless the remote command or application specifically requires terminal behavior.voidsendReqSetEnv(int channelNum, String name, String value)Requests that the server set environment variablenametovaluefor the session channel identified bychannelNum.voidsendReqShell(int channelNum)Starts a remote shell on the open session channel identified bychannelNum.voidsendReqSignal(int channelNum, String signalName)Requests delivery ofsignalNameto the remote process running onchannelNum.voidsendReqSubsystem(int channelNum, String subsystemName)Requests the predefined subsystem named bysubsystemNameon session channelchannelNum.voidsendReqWindowChange(int channelNum, int widthInChars, int heightInRows, int pixWidth, int pixHeight)Notifies the server that the terminal dimensions changed for the PTY associated withchannelNum.voidsendReqX11Forwarding(int channelNum, boolean singleConnection, String authProt, String authCookie, int screenNum)Sends an SSH X11-forwarding request on the session channel inchannelNum.voidsendReqXonXoff(int channelNum, boolean clientCanDo)Deprecated for practical use.voidsetAbortCurrent(boolean value)Sets theAbortCurrentproperty; seegetAbortCurrent().voidsetAllowedAlgorithms(JsonObject json)Applies an explicit allow-list of SSH negotiation algorithms supplied injson.voidsetCaretControl(boolean value)Sets theCaretControlproperty; seegetCaretControl().voidsetClientIdentifier(String value)Sets theClientIdentifierproperty; seegetClientIdentifier().voidsetClientIpAddress(String value)Sets theClientIpAddressproperty; seegetClientIpAddress().voidsetClientPort(int value)Sets theClientPortproperty; seegetClientPort().voidsetConnectTimeoutMs(int value)Sets theConnectTimeoutMsproperty; seegetConnectTimeoutMs().voidsetEnableCompression(boolean value)Sets theEnableCompressionproperty; seegetEnableCompression().voidsetEnableSecrets(boolean value)Sets theEnableSecretsproperty; seegetEnableSecrets().voidsetForceCipher(String value)Sets theForceCipherproperty; seegetForceCipher().voidsetHeartbeatMs(int value)Sets theHeartbeatMsproperty; seegetHeartbeatMs().voidsetHostKeyAlg(String value)Sets theHostKeyAlgproperty; seegetHostKeyAlg().voidsetHttpProxyAuthMethod(String value)Sets theHttpProxyAuthMethodproperty; seegetHttpProxyAuthMethod().voidsetHttpProxyDomain(String value)Sets theHttpProxyDomainproperty; seegetHttpProxyDomain().voidsetHttpProxyHostname(String value)Sets theHttpProxyHostnameproperty; seegetHttpProxyHostname().voidsetHttpProxyPassword(String value)Sets theHttpProxyPasswordproperty; seegetHttpProxyPassword().voidsetHttpProxyPort(int value)Sets theHttpProxyPortproperty; seegetHttpProxyPort().voidsetHttpProxyUsername(String value)Sets theHttpProxyUsernameproperty; seegetHttpProxyUsername().voidsetIdleTimeoutMs(int value)Sets theIdleTimeoutMsproperty; seegetIdleTimeoutMs().voidsetKeepSessionLog(boolean value)Sets theKeepSessionLogproperty; seegetKeepSessionLog().voidsetMaxPacketSize(int value)Sets theMaxPacketSizeproperty; seegetMaxPacketSize().voidsetPreferIpv6(boolean value)Sets thePreferIpv6property; seegetPreferIpv6().voidsetProgressListener(ProgressListener listener)Installs the listener that receives this object's progress events (abortCheck,percentDone,progressInfo) during its long-running methods; replaces any listener or lambda installed before;nullremoves it.voidsetReadTimeoutMs(int value)Sets theReadTimeoutMsproperty; seegetReadTimeoutMs().voidsetReqExecCharset(String value)Sets theReqExecCharsetproperty; seegetReqExecCharset().voidsetSocksHostname(String value)Sets theSocksHostnameproperty; seegetSocksHostname().voidsetSocksPassword(String value)Sets theSocksPasswordproperty; seegetSocksPassword().voidsetSocksPort(int value)Sets theSocksPortproperty; seegetSocksPort().voidsetSocksUsername(String value)Sets theSocksUsernameproperty; seegetSocksUsername().voidsetSocksVersion(int value)Sets theSocksVersionproperty; seegetSocksVersion().voidsetSoRcvBuf(int value)Sets theSoRcvBufproperty; seegetSoRcvBuf().voidsetSoSndBuf(int value)Sets theSoSndBufproperty; seegetSoSndBuf().voidsetStderrToStdout(boolean value)Sets theStderrToStdoutproperty; seegetStderrToStdout().voidsetStripColorCodes(boolean value)Sets theStripColorCodesproperty; seegetStripColorCodes().voidsetTcpNoDelay(boolean value)Sets theTcpNoDelayproperty; seegetTcpNoDelay().voidsetTtyMode(String ttyName, int ttyValue)Adds or updates one TTY mode to be included in a laterrequest.sendReqPty(int, String, int, int, int, int)voidsetUncommonOptions(String value)Sets theUncommonOptionsproperty; seegetUncommonOptions().voidsetUserAuthBanner(String value)Sets theUserAuthBannerproperty; seegetUserAuthBanner().startKeyboardAuth(String login)Begins keyboard-interactive authentication for the login inlogin.intwaitForChannelMessage(int pollTimeoutMs)Waits for the next SSH channel message on any channel.Methods inherited from class com.chilkatsoft.chilkat2.ChilkatObject
close, getDebugLogFilePath, getLastErrorHtml, getLastErrorText, getLastErrorXml, getLastMethodSuccess, getVerboseLogging, getVersion, isClosed, setDebugLogFilePath, setLastMethodSuccess, setVerboseLogging, toString
-
Constructor Details
-
Ssh
public Ssh()Creates a newSshobject.
-
-
Method Details
-
getAbortCurrent
public boolean getAbortCurrent()Set totrueto request that the currently running Chilkat operation abort. This applies to synchronous and asynchronous methods that may block on network or lengthy processing.A synchronous call can be interrupted by setting this property from another thread. When the abort is observed, the current method returns failure, but the SSH connection and channel are not automatically closed. Bytes already buffered remain available, the remote process can continue running, and a later receive call can continue on the same channel. The same object and connection can also be used to open new channels afterward.
An aborted receive does not set
orgetDisconnectCode(), and object-level configuration settings remain unchanged. An abortedgetDisconnectReason()leaves the object disconnected but reusable for a later connection attempt.connect(String, int)When the abort is observed, Chilkat resets the property to
false. If no operation is running, it is reset when the next method begins.- Returns:
- the value of the
AbortCurrentproperty
-
setAbortCurrent
public void setAbortCurrent(boolean value)Sets theAbortCurrentproperty; seegetAbortCurrent().- Parameters:
value- the new value
-
getAuthFailReason
public int getAuthFailReason()Contains the result code from the most recent call to an SSH authentication method, including,authenticatePw(String, String),authenticatePk(String, SshKey), and theirauthenticatePwPk(String, String, SshKey)SecureStringvariants. The initial value is0, and a successful authentication resets it to0. A failed attempt sets one of the following values.Value Meaning
1Transport failure. The connection is unavailable, communication was lost, or a read operation failed or timed out. Calling an authentication method beforealso produces this value.connect(String, int)2Invalid key for public-key authentication. For example, theSshKeyis empty, public-only, malformed, unsupported, or otherwise unsuitable.3No mutually supported authentication method was available.4SSH authentication protocol error. An unexpected or invalid message was received.5The password or private key was rejected by the server.6The SSH session is already authenticated.7The server requires a password change. See.getPasswordChangeRequested()This property is not cleared by unrelated operations such as
orsendIgnore(). Read it immediately after an authentication method returns. If the server closes the connection because of an authentication-attempt limit, the result may bedisconnect()1; inspect,getDisconnectCode(), andgetDisconnectReason()LastErrorText.- Returns:
- the value of the
AuthFailReasonproperty (read-only)
-
getCaretControl
public boolean getCaretControl()Controls whether recognized caret notation is converted to ASCII control characters in strings passed toandsendReqExec(int, String). The default ischannelSendString(int, String, String)false.When set to
true, recognized uppercase sequences such as^C,^M,^?, and^^are translated before the text is sent. An unrecognized sequence, such as lowercase^a, is sent literally.Caret Dec Hex Name Description ^@ 0 00 NUL Null ^A 1 01 SOH Start of Heading ^B 2 02 STX Start of Text ^C 3 03 ETX End of Text ^D 4 04 EOT End of Transmission ^E 5 05 ENQ Enquiry ^F 6 06 ACK Acknowledge ^G 7 07 BEL Bell ^H 8 08 BS Backspace ^I 9 09 HT Horizontal Tab ^J 10 0A LF Line Feed ^K 11 0B VT Vertical Tab ^L 12 0C FF Form Feed ^M 13 0D CR Carriage Return ^N 14 0E SO Shift Out ^O 15 0F SI Shift In ^P 16 10 DLE Data Link Escape ^Q 17 11 DC1 Device Control One (XON) ^R 18 12 DC2 Device Control Two ^S 19 13 DC3 Device Control Three (XOFF) ^T 20 14 DC4 Device Control Four ^U 21 15 NAK Negative Acknowledge ^V 22 16 SYN Synchronous Idle ^W 23 17 ETB End of Transmission Block ^X 24 18 CAN Cancel ^Y 25 19 EM End of Medium ^Z 26 1A SUB Substitute ^[ 27 1B ESC Escape ^\ 28 1C FS File Separator ^] 29 1D GS Group Separator ^^ 30 1E RS Record Separator ^_ 31 1F US Unit Separator ^? 127 7F DEL Delete
- Returns:
- the value of the
CaretControlproperty
-
setCaretControl
public void setCaretControl(boolean value)Sets theCaretControlproperty; seegetCaretControl().- Parameters:
value- the new value
-
getChannelOpenFailCode
public int getChannelOpenFailCode()Contains the SSH channel-open failure code when the server rejects a request to open a channel. The values are defined by RFC 4254.Code Symbolic name
1SSH_OPEN_ADMINISTRATIVELY_PROHIBITED2SSH_OPEN_CONNECT_FAILED3SSH_OPEN_UNKNOWN_CHANNEL_TYPE4SSH_OPEN_RESOURCE_SHORTAGEThe initial value is
0. A local failure, such as attempting to open a channel before connecting, can also leave this property at0because no SSH channel-open failure message was received. Read this property immediately after a channel-open method returns-1.- Returns:
- the value of the
ChannelOpenFailCodeproperty (read-only)
-
getChannelOpenFailReason
Contains the descriptive text associated withwhen the server rejects a channel-open request. The text is supplied by the server and may be empty or generic. The initial value is an empty string.getChannelOpenFailCode()A rejected channel-open request normally leaves the underlying SSH connection open. Local failures that occur before a request reaches the server may leave both this property and
unchanged.getChannelOpenFailCode()- Returns:
- the value of the
ChannelOpenFailReasonproperty (read-only)
-
getClientIdentifier
Specifies the SSH client-identification string sent when a connection is established. The default isSSH-2.0-Chilkat_followed by the Chilkat version, for exampleSSH-2.0-Chilkat_11.6.0.The value should begin with
SSH-2.0-. A server may disconnect if the identification string is not valid.- Returns:
- the value of the
ClientIdentifierproperty
-
setClientIdentifier
Sets theClientIdentifierproperty; seegetClientIdentifier().- Parameters:
value- the new value (notnull)
-
getClientIpAddress
This property is normally left unset. Set it only when the computer has multiple network interfaces or multiple local IP addresses and the application needs to use a specific one.The value may be a numeric IPv4 or IPv6 address. Do not specify a domain name. When this property is empty, Chilkat and the operating system automatically select the appropriate local address.
The specified address must be available on the local computer and must be compatible with the address family used for the connection. If the address is invalid or unavailable, the connection fails.
This setting applies to all connection paths, including direct SSH connections, HTTP and SOCKS proxy connections,
, and multi-hop SSH connections.connectThroughSsh(Ssh, String, int)- Returns:
- the value of the
ClientIpAddressproperty
-
setClientIpAddress
Sets theClientIpAddressproperty; seegetClientIpAddress().- Parameters:
value- the new value (notnull)
-
getClientPort
public int getClientPort()This property is normally left at its default value of0. In this case, the operating system automatically chooses an unused local port from its ephemeral-port range. Applications should set a specific local port only when a remote system or network policy requires the connection to originate from that port.When set to a nonzero value, Chilkat requests that exact local port. The connection fails if the port is already in use or is otherwise unavailable. A specifically chosen port might also be temporarily unavailable for reuse after a connection closes because of operating-system TCP connection management. These port-reuse concerns do not normally apply when this property remains
0.This property applies to all connection paths, including direct SSH connections, HTTP and SOCKS proxy connections,
, and multi-hop SSH connections.connectThroughSsh(Ssh, String, int)Starting in Chilkat v11.6.0, assigned values must be in the range
0through65535. If a negative value or a value greater than65535is assigned, it is ignored and the existing property value remains unchanged.- Returns:
- the value of the
ClientPortproperty
-
setClientPort
public void setClientPort(int value)Sets theClientPortproperty; seegetClientPort().- Parameters:
value- the new value
-
getConnectTimeoutMs
public int getConnectTimeoutMs()Specifies the maximum number of milliseconds allowed for the remote endpoint to accept the TCP connection. The default is30000(30 seconds).A value of
0removes the Chilkat-imposed connect timeout; in practice, the attempt ends when the operating system reports that the connection failed. Negative values are treated as0.This timeout applies whether the destination is specified by a DNS hostname or an IP address, and to direct connections and connections made through HTTP proxies, SOCKS proxies, and
. ForconnectThroughSsh(Ssh, String, int)ConnectThroughSsh, the innerSshobject’s value is used.Scope: This property covers only TCP connection establishment. Proxy authentication, the SSH identification exchange, key exchange, and other server communication are controlled by
.getReadTimeoutMs()- Returns:
- the value of the
ConnectTimeoutMsproperty
-
setConnectTimeoutMs
public void setConnectTimeoutMs(int value)Sets theConnectTimeoutMsproperty; seegetConnectTimeoutMs().- Parameters:
value- the new value
-
getDisconnectCode
public int getDisconnectCode()Contains the reason code from the most recent SSHDISCONNECTmessage received from the server. The values are defined by RFC 4253.The initial value is
0. It also remains0after a normal local, an ordinary TCP connection loss that did not include an SSHdisconnect()DISCONNECTmessage, a failed connection attempt, authentication rejection, receive timeout, receive abort, or rejected channel-open request.When the server sends an SSH
DISCONNECT, this property contains the server-provided code and remains available after. A subsequent call tocheckConnection()clears the value toconnect(String, int)0, whether that new attempt succeeds or fails.Code Symbolic name
1SSH_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT2SSH_DISCONNECT_PROTOCOL_ERROR3SSH_DISCONNECT_KEY_EXCHANGE_FAILED4SSH_DISCONNECT_RESERVED5SSH_DISCONNECT_MAC_ERROR6SSH_DISCONNECT_COMPRESSION_ERROR7SSH_DISCONNECT_SERVICE_NOT_AVAILABLE8SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED9SSH_DISCONNECT_HOST_KEY_NOT_VERIFIABLE10SSH_DISCONNECT_CONNECTION_LOST11SSH_DISCONNECT_BY_APPLICATION12SSH_DISCONNECT_TOO_MANY_CONNECTIONS13SSH_DISCONNECT_AUTH_CANCELLED_BY_USER14SSH_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE15SSH_DISCONNECT_ILLEGAL_USER_NAME- Returns:
- the value of the
DisconnectCodeproperty (read-only)
-
getDisconnectReason
Contains the descriptive text sent with the most recent server SSHDISCONNECTmessage. Seefor the corresponding RFC 4253 reason code.getDisconnectCode()The initial value is an empty string. It remains empty after a normal local
, an ordinary TCP connection loss without an SSHdisconnect()DISCONNECTmessage, a failed connection attempt, authentication rejection, receive timeout, receive abort, or rejected channel-open request.When a server-sent SSH
DISCONNECTis received, the text remains available after. A subsequent call tocheckConnection()clears it, whether the new attempt succeeds or fails. The returned string is empty rather than null when no reason is available.connect(String, int)- Returns:
- the value of the
DisconnectReasonproperty (read-only)
-
getEnableCompression
public boolean getEnableCompression()Controls whether SSH compression may be negotiated. The default istrue, meaning compression is used when the server supports it.Some older servers advertise compression but fail when it is enabled. If the server disconnects during or immediately after connection/authentication, try setting this property to
false.- Returns:
- the value of the
EnableCompressionproperty
-
setEnableCompression
public void setEnableCompression(boolean value)Sets theEnableCompressionproperty; seegetEnableCompression().- Parameters:
value- the new value
-
getEnableSecrets
public boolean getEnableSecrets()Enables automatic resolution of secret specification strings from secure operating-system storage. The default isfalse.When
true, supported password properties and authentication methods may receive a value beginning with!!instead of a literal credential. Chilkat resolves the secret from Windows Credential Manager on Windows or Apple Keychain on macOS.Secret specification format:
!![appName|]service[|domain]|username
This feature applies to
,getHttpProxyPassword(),getSocksPassword(), andauthenticatePw(String, String).authenticatePwPk(String, String, SshKey)- Returns:
- the value of the
EnableSecretsproperty
-
setEnableSecrets
public void setEnableSecrets(boolean value)Sets theEnableSecretsproperty; seegetEnableSecrets().- Parameters:
value- the new value
-
getForceCipher
Restricts SSH cipher negotiation to one cipher or a comma-separated preference list. Leave this property empty to let Chilkat choose the first mutually supported cipher from its normal preference order.Supported cipher names
chacha20-poly1305@openssh.comaes128-ctr,aes192-ctr,aes256-ctraes128-cbc,aes192-cbc,aes256-cbcaes128-gcm@openssh.com,aes256-gcm@openssh.comtwofish128-cbc,twofish256-cbcblowfish-cbc,3des-cbcarcfour128,arcfour256Cipher names must use the exact lowercase spelling shown above. If none of the specified ciphers is supported by the server,
fails.connect(String, int)- Returns:
- the value of the
ForceCipherproperty
-
setForceCipher
Sets theForceCipherproperty; seegetForceCipher().- Parameters:
value- the new value (notnull)
-
getHeartbeatMs
public int getHeartbeatMs()Specifies the interval, in milliseconds, betweenevent callbacks during operations that support progress events. The callback gives the application an opportunity to abort an operation before it completes.AbortCheckThe default is
0, which disables periodicAbortCheckcallbacks.- Returns:
- the value of the
HeartbeatMsproperty
-
setHeartbeatMs
public void setHeartbeatMs(int value)Sets theHeartbeatMsproperty; seegetHeartbeatMs().- Parameters:
value- the new value
-
getHostKeyAlg
Specifies the preferred host-key algorithm used during SSH connection establishment. The default isDSS; set it toRSAonly when required for compatibility with a particular server.Normally this property should be left unchanged.
- Returns:
- the value of the
HostKeyAlgproperty
-
setHostKeyAlg
Sets theHostKeyAlgproperty; seegetHostKeyAlg().- Parameters:
value- the new value (notnull)
-
getHostKeyFingerprint
Contains the connected server’s host-key fingerprint in Chilkat’s legacy MD5 format:ssh-ed25519 256 c8:73:22:c7:82:aa:09:f1:1c:4e:99:8a:a0:62:a7:87
The value consists of the SSH host-key type, key size, and the MD5 digest represented as colon-separated hexadecimal bytes. It is empty before a successful connection and after a normal
, a server-sent SSHdisconnect()DISCONNECT, or a failed connection attempt.After an abrupt TCP loss, a previously obtained fingerprint can temporarily remain even when
isgetIsConnected()false. Therefore, a nonempty value is not proof that the connection is currently usable. CheckIsConnectedbefore relying on per-session state.Server identity: Compare the fingerprint with a value obtained from a trusted source before sending credentials. For new applications, use
withgetHostKeyFP(String, boolean, boolean)SHA256.- Returns:
- the value of the
HostKeyFingerprintproperty (read-only)
-
getHttpProxyAuthMethod
Specifies the authentication method used by an HTTP proxy. Matching is case-insensitive.Value Behavior
empty Automatically negotiate a supported authentication method with the proxy.
BasicUse HTTP Basic authentication.NTLMUse NTLM authentication.Basic and NTLM are the supported methods. Chilkat automatically handles a
407 Proxy Authentication Requiredresponse and performs the required authentication exchange.NTLMv2 is used unless NTLMv1 is explicitly selected by setting
Global.DefaultNtlmVersionto1.- Returns:
- the value of the
HttpProxyAuthMethodproperty
-
setHttpProxyAuthMethod
Sets theHttpProxyAuthMethodproperty; seegetHttpProxyAuthMethod().- Parameters:
value- the new value (notnull)
-
getHttpProxyDomain
Specifies the optional Windows domain used for NTLM authentication with an HTTP proxy.The value is the legacy Windows NetBIOS domain name. It is not a DNS domain name and is not the workstation name. This property is ignored unless NTLM proxy authentication is used.
- Returns:
- the value of the
HttpProxyDomainproperty
-
setHttpProxyDomain
Sets theHttpProxyDomainproperty; seegetHttpProxyDomain().- Parameters:
value- the new value (notnull)
-
getHttpProxyHostname
Specifies the hostname or numeric IP address of an HTTP proxy.Chilkat uses the HTTP
CONNECTmethod to establish the SSH tunnel through the proxy. The TCP connection to the proxy is not itself protected by TLS for this SSH use case.The HTTP proxy is used only when
isgetSocksVersion()0, this property is nonempty, andis nonzero. A configured SOCKS proxy takes precedence. These settings apply to bothgetHttpProxyPort()andconnect(String, int).connectThroughSsh(Ssh, String, int)- Returns:
- the value of the
HttpProxyHostnameproperty
-
setHttpProxyHostname
Sets theHttpProxyHostnameproperty; seegetHttpProxyHostname().- Parameters:
value- the new value (notnull)
-
getHttpProxyPassword
Specifies the password used to authenticate with an HTTP proxy.If the proxy requires authentication and this property is empty, the connection fails.
- Returns:
- the value of the
HttpProxyPasswordproperty
-
setHttpProxyPassword
Sets theHttpProxyPasswordproperty; seegetHttpProxyPassword().- Parameters:
value- the new value (notnull)
-
getHttpProxyPort
public int getHttpProxyPort()Specifies the HTTP proxy port.An HTTP proxy is used only when
isgetSocksVersion()0,is nonempty, and this property is nonzero. A configured SOCKS proxy takes precedence.getHttpProxyHostname()Common proxy ports are:
8080— the most common general-purpose HTTP proxy port. It is non-privileged, so the proxy service typically does not require administrator or root privileges to bind to it.3128— commonly used by Squid and enterprise proxy infrastructure.8888— commonly used by development and debugging proxies such as Charles Proxy, Fiddler, and Burp Suite.
- Returns:
- the value of the
HttpProxyPortproperty
-
setHttpProxyPort
public void setHttpProxyPort(int value)Sets theHttpProxyPortproperty; seegetHttpProxyPort().- Parameters:
value- the new value
-
getHttpProxyUsername
Specifies the username used to authenticate with an HTTP proxy.If the proxy requires authentication and this property is empty, the connection fails.
- Returns:
- the value of the
HttpProxyUsernameproperty
-
setHttpProxyUsername
Sets theHttpProxyUsernameproperty; seegetHttpProxyUsername().- Parameters:
value- the new value (notnull)
-
getIdleTimeoutMs
public int getIdleTimeoutMs()Specifies an inactivity interval, in milliseconds, for SSH receive waits that use this property. The default is0, meaning no inactivity limit.This is not simply an application-output timeout. Receiving any SSH packet, including transport or channel-control traffic that contains no stdout or stderr bytes, counts as communication and restarts the interval. A remote command can therefore remain silent longer than this value without necessarily causing a timeout.
Timeout handling is method-specific. Methods having an explicit timeout argument, such as
andchannelPoll(int, int), use that argument for the corresponding wait. In v11.6.0 testing,waitForChannelMessage(int)usedchannelReadAndPoll(int, int)IdleTimeoutMsfor its initial read whenwasgetReadTimeoutMs()0.This property governs receiving. It is not a send-progress timeout.
- Returns:
- the value of the
IdleTimeoutMsproperty
-
setIdleTimeoutMs
public void setIdleTimeoutMs(int value)Sets theIdleTimeoutMsproperty; seegetIdleTimeoutMs().- Parameters:
value- the new value
-
getIsConnected
public boolean getIsConnected()Returnstruewhen Chilkat currently considers the SSH transport connected. It becomestrueafterestablishes the secure transport. It isconnect(String, int)falsebefore connecting, after, after a failed connection attempt, after a server-sent SSHdisconnect()DISCONNECT, or when socket closure is detected.An authentication failure, channel-open rejection, receive timeout, or aborted receive does not by itself set this property to
false. If the underlying transport remains usable, the application can retry the operation on the same connection.Reading this property can reflect a remote close that the operating system has already reported. In testing, it became
falsebeforewas called. However,checkConnection()truedoes not prove that the remote server is responsive or that a silent network failure has not occurred.To verify that SSH traffic can still be exchanged, call
and check its return value.sendIgnore()After abrupt transport loss or a server protocol disconnect, retained per-channel state can be stale even though this property is
false. TreatIsConnected =as authoritative for network I/O. Bytes received before the loss can remain available in a retained channel buffer.false- Returns:
- the value of the
IsConnectedproperty (read-only)
-
getKeepSessionLog
public boolean getKeepSessionLog()Controls whether SSH protocol traffic is accumulated in. The default isgetSessionLog()false. This object-level setting persists across disconnects, failed operations, and subsequent connections until changed by the application.The log for a completed session remains available after disconnect or transport loss. A later successful connection begins a new session log.
Session logging is intended for diagnostics. The log grows as a session proceeds, so disable it when no longer needed. Chilkat does not write literal authentication passwords or private-key passphrases to the session log, but diagnostic logs should still be handled as potentially sensitive.
- Returns:
- the value of the
KeepSessionLogproperty
-
setKeepSessionLog
public void setKeepSessionLog(boolean value)Sets theKeepSessionLogproperty; seegetKeepSessionLog().- Parameters:
value- the new value
-
getMaxPacketSize
public int getMaxPacketSize()Specifies the maximum SSH channel packet size advertised in theSSH_MSG_CHANNEL_OPENmessage. The default is8192.For high-volume transfers, a value such as
32768may improve performance.- Returns:
- the value of the
MaxPacketSizeproperty
-
setMaxPacketSize
public void setMaxPacketSize(int value)Sets theMaxPacketSizeproperty; seegetMaxPacketSize().- Parameters:
value- the new value
-
getNumOpenChannels
public int getNumOpenChannels()Returns the number of channel records in the active SSH channel collection. A channel is normally added after its open request is accepted and removed when final remote-close processing occurs.After
or transport loss, this property returnsdisconnect()0because former channels are no longer active or enumerable. Buffered data for a former channel can nevertheless remain retrievable by its channel number until it is released or a new connection clears it.A channel closed locally with
can havechannelSendClose(int)returnchannelIsOpen(int)falsewhile it is still counted until final cleanup. Conversely, a remotely closed channel can cease to be counted while its results are only temporarily retained.Result-lifetime warning: Querying this property is an SSH operation that can process pending final cleanup. After
or another completion receive returns, retrieve stdout, stderr, and exit status before readingchannelReceiveToClose(int)NumOpenChannels; otherwise the completed channel record can be discarded.Use
andgetChannelNumber(int)with zero-based indexes fromgetChannelType(int)0throughNumOpenChannels - 1. Do not assume every enumerated channel is still open for application I/O.- Returns:
- the value of the
NumOpenChannelsproperty (read-only)
-
getPasswordChangeRequested
public boolean getPasswordChangeRequested()Indicates that the server rejected password authentication because it requires the user to change the password. This property is set byandauthenticatePw(String, String).authenticatePwPk(String, String, SshKey)When
true, call the authentication method again and pass both passwords in this form:|oldPassword|newPassword|
- Returns:
- the value of the
PasswordChangeRequestedproperty (read-only)
-
getPreferIpv6
public boolean getPreferIpv6()Controls which address family is selected when DNS resolution for a hostname returns both an IPv4 address and an IPv6 address.- When
false(the default), Chilkat selects the IPv4 address when one is available. - When
true, Chilkat selects the IPv6 address when one is available.
This property expresses a preference; it does not prohibit use of the other address family when the preferred family is unavailable.
No address fallback: Chilkat attempts only the first address selected from the DNS results. If that connection attempt fails, it does not automatically try another resolved address or fall back to the other address family. For example, when IPv6 is preferred and the selected IPv6 connection fails, an available IPv4 address is not subsequently tried.
- Returns:
- the value of the
PreferIpv6property
- When
-
setPreferIpv6
public void setPreferIpv6(boolean value)Sets thePreferIpv6property; seegetPreferIpv6().- Parameters:
value- the new value
-
getReadTimeoutMs
public int getReadTimeoutMs()Specifies a receive timeout, in milliseconds, for SSH methods that use this property. The default is0, meaning noReadTimeoutMslimit.The exact scope is method-specific:
Method Observed timeout scope
Limits the wait for channel input.channelRead(int)Limits the initial wait when nonzero. After the first data arrives,channelReadAndPoll(int, int)pollTimeoutMscontrols the additional quiet-period wait.Limits the receive operation while waiting for channel closure.channelReceiveToClose(int)andchannelReceiveUntilMatch(int, String, String, boolean)Limits the wait for a matching pattern.channelReceiveUntilMatchN(int, StringArray, String, boolean)andchannelPoll(int, int)Use their explicitwaitForChannelMessage(int)pollTimeoutMsarguments instead.A receive timeout does not discard bytes already received. The connection and channel can remain usable, and a later receive call can continue. Always inspect and preserve buffered stdout and stderr after a timeout.
- Returns:
- the value of the
ReadTimeoutMsproperty
-
setReadTimeoutMs
public void setReadTimeoutMs(int value)Sets theReadTimeoutMsproperty; seegetReadTimeoutMs().- Parameters:
value- the new value
-
getReqExecCharset
Specifies the character encoding used for command text sent by,sendReqExec(int, String), andquickCommand(String, String). The default isquickCmdSend(String)ANSI.On Windows,
ANSIuses the Windows ANSI code page returned byGetACP, not the OEM code page. Its exact meaning on non-Windows platforms is environment-dependent. For portable behavior, specify an explicit charset such asutf-8orwindows-1252.This property applies to the command string itself. It does not override the explicit
charsetargument passed to.channelSendString(int, String, String)Use a supported charset name. In v11.6.0, an unrecognized charset name was observed to fall back to UTF-8 rather than fail; applications should not rely on that fallback.
- Returns:
- the value of the
ReqExecCharsetproperty
-
setReqExecCharset
Sets theReqExecCharsetproperty; seegetReqExecCharset().- Parameters:
value- the new value (notnull)
-
getServerIdentifier
Contains the SSH server-identification string received during connection establishment. For example:SSH-2.0-OpenSSH_8.9p1 Ubuntu-3ubuntu0.16
The initial value is an empty string. After a successful connection, the value remains available after a normal
, a server-sent SSHdisconnect()DISCONNECT, or an abrupt transport loss.A subsequent failed connection attempt clears this property rather than retaining the identifier from an earlier session. A successful reconnect replaces it with the newly received identifier. The empty result is an empty string, not null.
- Returns:
- the value of the
ServerIdentifierproperty (read-only)
-
getSessionLog
Contains the in-memory SSH protocol log for the current or most recently completed successful session. Enable logging by settingtogetKeepSessionLog()true.The initial value is an empty string. A normal disconnect, server disconnect, or transport loss leaves the existing session log available. A later successful
starts a new session log rather than appending indefinitely to the previous session. A failed TCP connection attempt does not necessarily replace an existing session log; inspectconnect(String, int)LastErrorTextfor the failed call.Authentication passwords and private-key passphrases are not included in the log. The log may contain server identifiers, negotiated algorithms, authentication method names, and other connection diagnostics.
This property contains log text; it is not a file path. Treat diagnostic output as potentially sensitive and avoid retaining it longer than necessary.
- Returns:
- the value of the
SessionLogproperty (read-only)
-
getSoRcvBuf
public int getSoRcvBuf()Specifies the socket receive-buffer size. The default is4194304bytes. Normally this property should remain unchanged.When download throughput is unexpectedly low, testing a larger value may help. Values should generally be multiples of
4096.When a proxy is used, this setting applies to the TCP connection made to the proxy.
- Returns:
- the value of the
SoRcvBufproperty
-
setSoRcvBuf
public void setSoRcvBuf(int value)Sets theSoRcvBufproperty; seegetSoRcvBuf().- Parameters:
value- the new value
-
getSoSndBuf
public int getSoSndBuf()Specifies the socket send-buffer size. The default is262144bytes. Normally this property should remain unchanged.When upload throughput is unexpectedly low, testing values such as
524288or1048576may help. Values should generally be multiples of4096.When a proxy is used, this setting applies to the TCP connection made to the proxy.
- Returns:
- the value of the
SoSndBufproperty
-
setSoSndBuf
public void setSoSndBuf(int value)Sets theSoSndBufproperty; seegetSoSndBuf().- Parameters:
value- the new value
-
getSocksHostname
Specifies the SOCKS proxy hostname or IPv4 address. This property is used only whenisgetSocksVersion()4or5. An IPv6 address cannot be used for the SOCKS proxy.SOCKS4a is not supported. With SOCKS5, the destination hostname is sent to the proxy and resolved remotely by the proxy. IPv6 destination addresses are not supported through SOCKS5.
- Returns:
- the value of the
SocksHostnameproperty
-
setSocksHostname
Sets theSocksHostnameproperty; seegetSocksHostname().- Parameters:
value- the new value (notnull)
-
getSocksPassword
Specifies the SOCKS5 password when username/password authentication is required. SOCKS4 does not define password authentication, so this property is ignored for SOCKS4.SOCKS5 supports either no authentication or username/password authentication. Leave both
and this property empty to request no authentication. The connection fails if the proxy requires an unsupported authentication method.getSocksUsername()- Returns:
- the value of the
SocksPasswordproperty
-
setSocksPassword
Sets theSocksPasswordproperty; seegetSocksPassword().- Parameters:
value- the new value (notnull)
-
getSocksPort
public int getSocksPort()Specifies the SOCKS proxy port. The default is1080. This property is used only whenisgetSocksVersion()4or5.- Returns:
- the value of the
SocksPortproperty
-
setSocksPort
public void setSocksPort(int value)Sets theSocksPortproperty; seegetSocksPort().- Parameters:
value- the new value
-
getSocksUsername
Specifies the SOCKS username. For SOCKS4, it is sent as the SOCKS user ID. For SOCKS5, it is used withfor username/password authentication.getSocksPassword()For SOCKS5, leave both properties empty to request no authentication.
- Returns:
- the value of the
SocksUsernameproperty
-
setSocksUsername
Sets theSocksUsernameproperty; seegetSocksUsername().- Parameters:
value- the new value (notnull)
-
getSocksVersion
public int getSocksVersion()Selects whether and how a SOCKS proxy is used.Value Behavior
0Do not use a SOCKS proxy. This is the default. Chilkat may still use an HTTP proxy if bothandgetHttpProxyHostname()are set.getHttpProxyPort()4Connect through a SOCKS4 proxy. SOCKS4a is not supported.5Connect through a SOCKS5 proxy.Proxy selection: A SOCKS proxy takes precedence over an HTTP proxy. When this property is
4or5, Chilkat uses the configured SOCKS proxy. When it is0, Chilkat uses an HTTP proxy only ifHttpProxyHostnameis nonempty andHttpProxyPortis nonzero. Otherwise, Chilkat connects directly to the SSH server.Assigning a value other than
4or5sets the property to0. These proxy settings apply to bothandconnect(String, int).connectThroughSsh(Ssh, String, int)- Returns:
- the value of the
SocksVersionproperty
-
setSocksVersion
public void setSocksVersion(int value)Sets theSocksVersionproperty; seegetSocksVersion().- Parameters:
value- the new value
-
getStderrToStdout
public boolean getStderrToStdout()Controls whether SSH extended-data received as stderr is merged into the normal channel receive buffer. The default istrue.When
true, retrieve combined stdout and stderr with,GetReceivedData,GetReceivedDataN, orgetReceivedText(int, String). WhengetReceivedTextS(int, String, String)false, retrieve SSH stderr separately withorGetReceivedStderr.getReceivedStderrText(int, String)The setting is applied when each incoming stderr packet is processed. Changing it while a channel is active affects only stderr received afterward. Already separated stderr is not moved into stdout, and already merged stderr cannot later be separated.
Read-method return values count bytes in both the normal and separate stderr buffers.
counts only the normal receive buffer.getReceivedNumBytes(int)This setting also affects
. WhenquickCommand(String, String)false, its returned string contains stdout but does not include separately received stderr.PTY channels: When a pseudo-terminal is allocated, the remote terminal normally combines the process's stdout and stderr into a single PTY byte stream before SSH transports it. In that case both appear in the normal receive buffer and the stderr buffer is empty regardless of this property.
- Returns:
- the value of the
StderrToStdoutproperty
-
setStderrToStdout
public void setStderrToStdout(boolean value)Sets theStderrToStdoutproperty; seegetStderrToStdout().- Parameters:
value- the new value
-
getStripColorCodes
public boolean getStripColorCodes()Controls whether terminal control sequences are removed from received text, so that the text returned is plain text. It applies to,getReceivedText(int, String)andgetReceivedSb(int, String, StringBuilder). The default isgetReceivedTextS(int, String, String)true.These are removed:
- CSI sequences:
ESC[, then optional parameter and intermediate bytes, then a final byte. These include colors and text styles (ESC[1;31m,ESC[38:5:196m), cursor movement and erasing (ESC[H,ESC[K,ESC[2J), mode changes such as bracketed paste (ESC[?2004h), and terminal queries (ESC[6n). - OSC, DCS, SOS, PM and APC strings, ended by
ESC\or BEL. For example, window titles (ESC]0;title), and the OSC 3008 context sequences that newer versions of systemd send around shell prompts. - Other escape sequences, such as
ESC 7,ESC 8,ESC =,ESC >andESC ( B. - The BEL, SO and SI control characters.
Line breaks (CR and LF), tabs and all other text are kept. 8-bit C1 control bytes such as
0x9Bare not removed, because those byte values also occur within UTF-8 characters. A malformed sequence loses only its ESC.A sequence split across SSH packets is still removed: if the received text ends with an unfinished sequence, those bytes are held back and returned with the text received next. They are returned as received if the channel has received EOF or CLOSE, or the connection was lost. An unusually long sequence (over 256 bytes for CSI, or over 16384 bytes for a control string) is not held back; only its ESC is removed.
For
GetReceivedTextS, stripping applies to both the literal substring search and the returned value; the corresponding original raw escape-sequence bytes are consumed.It does not affect raw-byte getters,
, pattern matching inpeekReceivedText(int, String), or the string returned bychannelReceiveUntilMatch(int, String, String, boolean).quickCommand(String, String)Only escape sequences and the control characters listed above are removed. Text that the server sends as plain characters stays: for example, the
%and spaces that zsh writes before a prompt (itsPROMPT_SPoption).- Returns:
- the value of the
StripColorCodesproperty
- CSI sequences:
-
setStripColorCodes
public void setStripColorCodes(boolean value)Sets theStripColorCodesproperty; seegetStripColorCodes().- Parameters:
value- the new value
-
getTcpNoDelay
public boolean getTcpNoDelay()Controls theTCP_NODELAYsetting for the underlying TCP connection. The default istrue, which disables the Nagle algorithm and generally improves responsiveness when many small messages are exchanged.When a proxy is used, this setting applies to the TCP connection made to the proxy.
- Returns:
- the value of the
TcpNoDelayproperty
-
setTcpNoDelay
public void setTcpNoDelay(boolean value)Sets theTcpNoDelayproperty; seegetTcpNoDelay().- Parameters:
value- the new value
-
getUncommonOptions
Provides comma-separated compatibility and security options for uncommon SSH scenarios. The default is an empty string, which is appropriate for most applications.Keyword Effect
ForceUserAuthRsaSha1Forcesssh-rsa/SHA-1 for RSA user authentication. Set before connecting when a server advertises RSA-SHA2 but still requires the legacy SHA-1 user-auth signature.no-weak-mac-algsRemoveshmac-sha1-96,hmac-sha1,hmac-md5, andhmac-ripemd160from the offered MAC algorithms.ProtectFromVpnOn Android, bypasses an installed or active VPN.+ssh-hmac-etmRe-enables Encrypt-then-MAC algorithms that are disabled by default as a Terrapin mitigation.+chacha20-poly1305@openssh.comRe-enableschacha20-poly1305@openssh.com, which is disabled by default as a Terrapin mitigation.Set connection-negotiation options before calling
.connect(String, int)- Returns:
- the value of the
UncommonOptionsproperty
-
setUncommonOptions
Sets theUncommonOptionsproperty; seegetUncommonOptions().- Parameters:
value- the new value (notnull)
-
getUserAuthBanner
Contains a user-authentication banner received from the server during authentication. Check this property afteror another authentication attempt and display it to the user when appropriate.startKeyboardAuth(String)This is per-authentication runtime state, not a persistent connection setting. A value assigned by the application can remain before authentication begins, including across a failed connection attempt, but an authentication attempt clears or replaces the value. In testing, both successful and rejected password authentication cleared a previously assigned value when the server sent no banner.
When no banner is available, the property returns an empty string rather than null.
- Returns:
- the value of the
UserAuthBannerproperty
-
setUserAuthBanner
Sets theUserAuthBannerproperty; seegetUserAuthBanner().- Parameters:
value- the new value (notnull)
-
authenticatePk
Authenticates an active, unauthenticated SSH connection using public-key authentication.usernameidentifies the server account, andprivateKeymust contain the corresponding private key. The public key must already be authorized for that account on the server.An empty or public-only
SshKeyis rejected locally withequal togetAuthFailReason()2; this local validation failure does not close the SSH connection.If the server rejects the key but keeps the connection open, the application may retry on the same connection with another private key or a different authentication method. The server may instead disconnect after an authentication-attempt limit is reached. Reconnect before retrying when
isgetIsConnected()false.Calling this method before
fails with reasonconnect(String, int)1. Calling it after the session is already authenticated fails with reason6.After a failure, inspect
,getAuthFailReason()LastErrorText, and, if the connection was closed,.getDisconnectReason()- Parameters:
username- theusernameargument (notnull)privateKey- theprivateKeyargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
authenticatePw
Authenticates an active, unauthenticated SSH connection usingloginandpassword.Call
first. Calling this method without a connection fails withconnect(String, int)equal togetAuthFailReason()1. Calling it after the session is already authenticated fails with reason6.If authentication fails and the server keeps the SSH connection open,
remainsgetIsConnected()trueand the application may retry on the same connection with corrected credentials or a different authentication method. A later correct password succeeded on the same connection in testing. A server can disconnect after too many failed attempts; reconnect before retrying whenIsConnectedisfalse.An authentication attempt clears or replaces
. Object-level configuration settings remain unchanged.getUserAuthBanner()If the server requests a password change, see
.getPasswordChangeRequested()After a failure, inspect
andgetAuthFailReason()LastErrorText.andgetDisconnectCode()remain zero and empty unless the server actually sends an SSHgetDisconnectReason()DISCONNECT.- Parameters:
login- theloginargument (notnull)password- thepasswordargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
authenticatePwPk
Authenticates with a server that requires both a password and a private key.usernameis the username,passwordis the password, andprivateKeyis the private key.Most servers require either password or public-key authentication rather than both. After a failure, inspect
andgetAuthFailReason()LastErrorText.- Parameters:
username- theusernameargument (notnull)password- thepasswordargument (notnull)privateKey- theprivateKeyargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
authenticateSecPw
Performs the same authentication as, but receives the login and password inauthenticatePw(String, String)SecureStringobjects.The connection-state, retry, timeout, and
behavior is the same as forgetAuthFailReason()AuthenticatePw.- Parameters:
login- theloginargument (notnull)password- thepasswordargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
authenticateSecPwPk
Performs the same combined password/private-key authentication as, but receives the username and password inauthenticatePwPk(String, String, SshKey)SecureStringobjects.- Parameters:
username- theusernameargument (notnull)password- thepasswordargument (notnull)privateKey- theprivateKeyargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
channelIsOpen
public boolean channelIsOpen(int channelNum)ReturnstruewhenchannelNumidentifies a channel that Chilkat currently considers open for application I/O; otherwise returnsfalse. It returnsfalsefor invalid or nonexistent channel numbers, after a normal local, after remote closure is processed, and immediately afterdisconnect()closes the channel locally.channelSendClose(int)can temporarily continue counting a locally closed channel until final remote-close processing occurs.getNumOpenChannels()Connection loss: After abrupt transport loss or a server-sent SSH
DISCONNECT, a retained channel record can temporarily cause this method to returntrueeven thoughisgetIsConnected()false. TreatIsConnected =as authoritative. Buffered bytes from before the loss can still be retrievable.false- Parameters:
channelNum- thechannelNumargument- Returns:
- the result; this method never throws
ChilkatException
-
channelPoll
public int channelPoll(int channelNum, int pollTimeoutMs)PollschannelNumfor incoming SSH channel messages, waiting at mostpollTimeoutMsmilliseconds. Pass0for a nonblocking poll. The explicitpollTimeoutMscontrols this wait; shorter values oforgetReadTimeoutMs()do not shorten it.getIdleTimeoutMs()Data received is appended to the normal receive buffer or separate stderr buffer according to
.getStderrToStdout()Return value Meaning
-1An error occurred. InspectLastErrorText,, andgetIsConnected().channelIsOpen(int)-2No additional applicable channel message arrived before the applicable timeout. Previously buffered stdout or stderr can still be available.0EOF or channel closure was processed. Buffered data can still remain and should be drained.> 0The total number of bytes currently buffered for the channel, counting both the normal receive buffer and a separate stderr buffer. It is not the number of bytes newly received by this call.The return value is not a newly received byte count. Inspect
, retrieve separate stderr when applicable, and check EOF, CLOSE, and exit-status flags. Processing a final channel message can remove a completed channel record, so drain buffered output before polling again.getReceivedNumBytes(int)- Parameters:
channelNum- thechannelNumargumentpollTimeoutMs- thepollTimeoutMsargument- Returns:
- the result (see
ChilkatObject.getLastMethodSuccess()where the description mentions failure)
-
channelRead
public int channelRead(int channelNum)Reads incoming SSH channel messages forchannelNum. A nonzerolimits the wait for channel input. Received data is appended to the normal receive buffer or separate stderr buffer according togetReadTimeoutMs().getStderrToStdout()Return value Meaning
-1An error occurred. InspectLastErrorText,, andgetIsConnected().channelIsOpen(int)-2No additional applicable channel message arrived before the applicable timeout. Previously buffered stdout or stderr can still be available.0EOF or channel closure was processed. Buffered data can still remain and should be drained.> 0The total number of bytes currently buffered for the channel, counting both the normal receive buffer and a separate stderr buffer. It is not the number of bytes newly received by this call.A timeout returns
-2rather than closing the channel. A later read can continue on the same channel.Because all channels share one SSH transport, this method can also process and buffer packets for other open channels while waiting for
channelNum.- Parameters:
channelNum- thechannelNumargument- Returns:
- the result (see
ChilkatObject.getLastMethodSuccess()where the description mentions failure)
-
channelReadAndPoll
public int channelReadAndPoll(int channelNum, int pollTimeoutMs)ReadschannelNumin two phases:- Waits for the first applicable channel message. A nonzero
limits this initial wait. WhengetReadTimeoutMs()ReadTimeoutMsis0,can provide the initial-read timeout.getIdleTimeoutMs() - After data begins arriving, continues processing until no additional data arrives for
pollTimeoutMsmilliseconds.
The second phase is governed by
pollTimeoutMs; a shorterReadTimeoutMsdoes not shorten that quiet-period wait.This pattern is useful for shell commands: allow a longer wait for the first output, then stop shortly after the output stream becomes idle.
Return value Meaning
-1An error occurred. InspectLastErrorText,, andgetIsConnected().channelIsOpen(int)-2No additional applicable channel message arrived before the applicable timeout. Previously buffered stdout or stderr can still be available.0EOF or channel closure was processed. Buffered data can still remain and should be drained.> 0The total number of bytes currently buffered for the channel, counting both the normal receive buffer and a separate stderr buffer. It is not the number of bytes newly received by this call.The method can return
0or-2while bytes remain buffered. Drain the normal and stderr buffers based on their actual contents, not solely on the method return value.- Parameters:
channelNum- thechannelNumargumentpollTimeoutMs- thepollTimeoutMsargument- Returns:
- the result (see
ChilkatObject.getLastMethodSuccess()where the description mentions failure)
- Waits for the first applicable channel message. A nonzero
-
channelReadAndPoll2
public int channelReadAndPoll2(int channelNum, int pollTimeoutMs, int maxNumBytes)Works like, but also returns after newly processed data causes the total buffered channel data to reach or exceedchannelReadAndPoll(int, int)maxNumBytes.maxNumBytesis a return threshold, not a hard receive-buffer limit. An entire SSH packet can be buffered, so the amount returned can exceed the requested threshold. Data already buffered before the call does not by itself cause an immediate threshold return.A value of
0or a negative value does not impose a useful threshold. For streaming large output, use a positive threshold, drain the buffer after each call, and perform a final drain when EOF or CLOSE is observed.Return value Meaning
-1An error occurred. InspectLastErrorText,, andgetIsConnected().channelIsOpen(int)-2No additional applicable channel message arrived before the timeout. Previously buffered stdout or stderr can still be available.0EOF or channel closure was processed. Buffered data can still remain and should be drained.> 0The total number of bytes currently buffered for the channel, counting both the normal receive buffer and a separate stderr buffer. It is not the number of bytes newly received by this call.- Parameters:
channelNum- thechannelNumargumentpollTimeoutMs- thepollTimeoutMsargumentmaxNumBytes- themaxNumBytesargument- Returns:
- the result (see
ChilkatObject.getLastMethodSuccess()where the description mentions failure)
-
channelReceiveToClose
public void channelReceiveToClose(int channelNum)Receives data onchannelNumuntil the server sends and Chilkat processes channelCLOSE. The server can send EOF earlier; EOF alone does not complete this method.Both normal data and stderr are processed. Stderr is merged or kept separate according to
. A nonzerogetStderrToStdout()limits the receive operation.getReadTimeoutMs()is not a simple stdout/stderr inactivity timer because any SSH communication can restart it.getIdleTimeoutMs()If the method times out or is canceled, bytes received before the failure remain buffered, the SSH connection and channel can remain open, and a later call can continue receiving on the same channel. These outcomes do not set
orgetDisconnectCode(). If the SSH transport is lost, the method fails andgetDisconnectReason()becomesgetIsConnected()false, but bytes received before the loss can still remain retrievable.This method buffers all received output in memory. It successfully accumulated at least 8 MiB in testing, but no upper limit was established. For potentially large or unbounded output, use incremental reads and drain the buffers as data arrives.
Retrieve completed-channel results immediately. After this method returns, get stdout, stderr, and exit status before calling unrelated SSH methods or querying
. A later SSH operation can finalize and discard the completed channel record.getNumOpenChannels()A
truereturn means the SSH receive operation completed. It does not mean the remote command exited successfully.- Parameters:
channelNum- thechannelNumargument- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
channelReceiveUntilMatch
public void channelReceiveUntilMatch(int channelNum, String matchPattern, String charset, boolean caseSensitive)Receives text onchannelNumuntil the accumulated text matchesmatchPattern. Existing buffered text is checked before waiting for additional network data.The supported pattern syntax consists of literal characters plus
*, which matches zero or more characters and can span line breaks. It can appear anywhere in the pattern. The?wildcard and bracket character classes are not supported, and backslash does not escape a literal*. A pattern containing only*waits until at least some text has arrived rather than matching an empty buffer immediately.charsetspecifies the character encoding, andcaseSensitivecontrols comparison. The method can read beyond the matched text because an entire SSH packet may already be available.Matching considers stderr even when
isgetStderrToStdout()false.is not applied before matching.getStripColorCodes()A nonzero
limits the wait.getReadTimeoutMs()is not a substitute for this limit because unrelated SSH traffic can restart the inactivity interval.getIdleTimeoutMs()Usage notes:
- Use distinctive literal sentinels when exact command boundaries are required.
- After success,
can remove and return text through a known literal terminator.getReceivedTextS(int, String, String) - Avoid an empty
matchPattern; it does not define a useful boundary.
- Parameters:
channelNum- thechannelNumargumentmatchPattern- thematchPatternargument (notnull)charset- thecharsetargument (notnull)caseSensitive- thecaseSensitiveargument- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
channelReceiveUntilMatchN
public void channelReceiveUntilMatchN(int channelNum, StringArray matchPatterns, String charset, boolean caseSensitive)Works like, but returns when any pattern inchannelReceiveUntilMatch(int, String, String, boolean)matchPatternsis matched. The array must contain at least one element.The first matching content encountered in the received stream determines when the method returns; array order does not override an earlier token in the stream. Existing buffered text is checked before waiting. Empty elements are ignored, and duplicate patterns are allowed.
The method does not return the index or value of the pattern that matched, and
does not identify it. After success, inspect the buffered text or use distinct nonoverlapping sentinels that the application can identify reliably.getLastJsonData(JsonObject)The same pattern grammar, stderr behavior, and
behavior described forgetReadTimeoutMs()ChannelReceiveUntilMatchapply.- Parameters:
channelNum- thechannelNumargumentmatchPatterns- thematchPatternsargument (notnull)charset- thecharsetargument (notnull)caseSensitive- thecaseSensitiveargument- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
channelReceivedClose
public boolean channelReceivedClose(int channelNum)Returnstrueif an SSHCLOSEmessage has been received forchannelNum. Remote CLOSE is distinct from EOF and closes the channel in both directions. When it is processed,becomeschannelIsOpen(int)falseand the channel is normally removed from.getNumOpenChannels()Returns
falsefor an invalid, released, locally disconnected, or no-longer-retained channel number. A transport can be lost without receiving a channel CLOSE; checkseparately.getIsConnected()Retrieve buffered output, stderr, and exit status promptly after the receive method completes and before calling
.channelRelease(int)- Parameters:
channelNum- thechannelNumargument- Returns:
- the result; this method never throws
ChilkatException
-
channelReceivedEof
public boolean channelReceivedEof(int channelNum)Returnstrueif an SSHEOFmessage has been received forchannelNum. EOF means the server will send no more ordinary channel data. It does not close the channel.The server can send EOF before it sends
CLOSE. During that interval, this method istrue,ischannelReceivedClose(int)false, and the channel can remain open and counted by. Exit status and CLOSE can arrive later.getNumOpenChannels()Returns
falsefor an invalid, released, disconnected, or no-longer-retained channel number. After transport failure, channel flags can be stale or unavailable; checkfirst.getIsConnected()- Parameters:
channelNum- thechannelNumargument- Returns:
- the result; this method never throws
ChilkatException
-
channelReceivedExitStatus
public boolean channelReceivedExitStatus(int channelNum)Returnstrueif the server supplied an exit-status value forchannelNum. Whentrue, call.getChannelExitStatus(int)Exit status is independent of EOF and CLOSE. It can arrive after EOF and before or with CLOSE. The server is not required to send an exit status for every channel type or command.
Returns
falsefor an invalid, released, disconnected, or no-longer-retained channel number. A connection failure does not synthesize an exit status.Check this flag and retrieve the value immediately after the receive method completes. A later unrelated SSH operation, including channel enumeration, can finalize and remove the completed channel record.
- Parameters:
channelNum- thechannelNumargument- Returns:
- the result; this method never throws
ChilkatException
-
channelRelease
public void channelRelease(int channelNum)Releases Chilkat’s retained local resources forchannelNumafter all required output and exit information has been retrieved. It does not send EOF or CLOSE and is not a channel-closing method.Calling it while a channel is still protocol-open has no effect. It can also be called after
to discard buffered data retained for a former channel. After release, methods such asdisconnect()report that the channel is unavailable.getReceivedNumBytes(int)Calling this method with an invalid channel number is a harmless no-op. Repeated calls are harmless.
Do not release a completed channel until stdout, stderr, and exit status have been retrieved. Also avoid unrelated SSH calls between completion and result retrieval because they can finalize and remove the completed channel record.
ChannelReceiveToClose(channelNum) GetReceivedText(...) GetReceivedStderrText(...) if (ChannelReceivedExitStatus(channelNum)) GetChannelExitStatus(channelNum) ChannelRelease(channelNum)- Parameters:
channelNum- thechannelNumargument
-
channelSendClose
public void channelSendClose(int channelNum)Sends an SSHCLOSEmessage forchannelNumand immediately marks the channel locally closed. The method does not wait for remote EOF, remote CLOSE, or an exit status, and it does not guarantee that the remote process has terminated.After a successful call,
returnschannelIsOpen(int)false, butcan continue counting the channel until final remote-close processing occurs. A repeated call can succeed while the local channel record remains; after the remote CLOSE removes the channel, another call fails because the channel no longer exists.getNumOpenChannels()For normal exec completion, prefer receiving through the remote CLOSE so all output and exit information can be collected. Use this method when the application intentionally abandons or closes the channel early.
- Parameters:
channelNum- thechannelNumargument- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
channelSendEof
public void channelSendEof(int channelNum)Sends an SSHEOFmessage onchannelNum. This closes only the client-to-server data direction. The application may continue receiving stdout, stderr, exit status, EOF, and CLOSE from the server.After EOF is sent, do not call
orChannelSendDataagain for that channel. A later send call can returnchannelSendString(int, String, String)trueeven though the data is not delivered to the remote process. Repeated calls toChannelSendEofare harmless but unnecessary.For an exec request that reads standard input, EOF is the normal way to indicate that all input has been supplied.
- Parameters:
channelNum- thechannelNumargument- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
channelSendString
EncodestextDatausingcharset, then sends the resulting bytes onchannelNum. No line ending or terminator is added automatically.An empty string is valid and sends zero bytes. When
isgetCaretControl()true, recognized caret sequences are translated to control characters before sending.On Windows,
ANSIuses the Windows ANSI code page returned byGetACP, not the OEM code page. Its meaning on other platforms is environment-dependent. Use an explicit charset such asutf-8orwindows-1252for portable behavior.Use a supported charset name. In v11.6.0, an unrecognized charset name was observed to fall back to UTF-8 rather than fail; applications should not rely on that fallback.
The method handles SSH packet sizing and channel-window flow control internally. It does not expose a partial-byte count if an error occurs.
Do not call this method after
. A successful return after EOF does not guarantee that the text was delivered.channelSendEof(int)See Supported Charsets.
- Parameters:
channelNum- thechannelNumargumenttextData- thetextDataargument (notnull)charset- thecharsetargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
checkConnection
public boolean checkConnection()Returnstruewhen the underlying SSH transport currently appears connected, andfalsewhen the object is unconnected, has been disconnected, a connection attempt failed, or transport loss has already been detected.In testing, this method returned immediately and matched
. It should not be treated as an end-to-end SSH round trip or proof that the remote server is responsive. UsegetIsConnected()when an active SSH exchange is required.sendIgnore()This method does not authenticate the session. A failed authentication, receive timeout, receive abort, or rejected channel-open request can leave it returning
truebecause those failures do not necessarily close the transport.A
falseresult can simply mean that no connection exists. The method does not necessarily replaceLastErrorText, so an existing error string may describe an earlier operation.Returns
trueif the underlying TCP socket does not currently appear to be closed, orfalseif the connection is known to be closed or invalid.Unlike
, which reports the connection state already known by thegetIsConnected()Sshobject, this method performs an additional non-consuming check of the socket. It calls the operating system'srecvfunction withMSG_PEEKto inspect up to one byte without removing any data from the socket's receive buffer.Important: This is a local socket-state check. It does not send an SSH message, wait for an SSH response, authenticate the session, or prove that the remote SSH server is responsive. For example, it may still return
truewhen the network path is silently broken but the operating system has not yet detected the failure. Usewhen an active SSH round trip is required.sendIgnore()A receive timeout, aborted operation, authentication failure, or rejected channel request does not necessarily close the socket. In those cases,
CheckConnectionmay continue to returntrue.A
falseresult can simply mean that no connection exists. This method may not replaceLastErrorTextwhen no new socket error is generated, so the existing diagnostic text can describe an earlier operation.- Returns:
- the result; this method never throws
ChilkatException
-
clearTtyModes
public void clearTtyModes()Clears all TTY mode settings previously added with. The nextsetTtyMode(String, int)request will not include those cleared modes.sendReqPty(int, String, int, int, int, int) -
connect
Establishes an SSH connection todomainNameon the TCP port specified byport. ThedomainNamemay be a DNS hostname or a numeric IPv4 or IPv6 address. A null or emptydomainNameis treated as a zero-length hostname and causes the call to fail.Proxy selection: If
isgetSocksVersion()4or5, Chilkat connects through the configured SOCKS proxy. Otherwise, ifis nonempty andgetHttpProxyHostname()is nonzero, Chilkat connects through the HTTP proxy. If neither condition applies, Chilkat connects directly to the SSH server.getHttpProxyPort()Connection state after success: A successful call means the TCP connection and secure SSH transport are established. The client and server identification strings have been exchanged, key exchange has completed, and the server host key has been received and cryptographically verified as part of the SSH key exchange. User authentication has not yet started, so every newly connected session is unauthenticated. Next call an authentication method such as
,authenticatePw(String, String),authenticatePk(String, SshKey), orauthenticatePwPk(String, String, SshKey).startKeyboardAuth(String)If this method is called while the object is already connected, Chilkat first disconnects the existing session and then establishes a new connection. This occurs even when connecting again to the same server. The existing connection and active channel collection are replaced. A new connection attempt also clears retained data belonging to channels from an earlier disconnected or lost session.
The same
Sshobject may be reused after, connection refusal, connect timeout, connect abort, server protocol disconnect, or abrupt transport loss. A failed call leavesdisconnect()equal togetIsConnected()false. Every successful new connection is unauthenticated and must be authenticated again. Channel numbers are opaque and can continue increasing across reconnects; do not assume they restart at zero.Persistent configuration: Representative writable settings remained unchanged across normal disconnects, failed connection attempts, authentication failures, receive timeouts and aborts, rejected channel opens, server disconnects, transport loss, and subsequent reconnects. Tested settings included connection and receive timeouts, socket settings, proxy-independent client settings, logging options, character-set and output options, compression, and uncommon options. Runtime state such as authentication, channels, disconnect diagnostics, host-key state, authentication banners, and session-log contents has a separate lifecycle. Typical state sequence: disconnected → SSH transport connected → authenticated → channels open. The operations valid in each state follow the SSH protocol.
Supported negotiation algorithms include:
Category Algorithms
Host key
ssh-ed25519,rsa-sha2-256,rsa-sha2-512,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-rsa,ssh-dssKey exchange
curve25519-sha256,curve25519-sha256@libssh.org, NIST ECDH, DH group 1/14/16/18, and group-exchange SHA-1/SHA-256Ciphers AES CTR/CBC/GCM, Twofish CBC, Blowfish CBC, and optionally
chacha20-poly1305@openssh.comMAC SHA-2, SHA-1, RIPEMD-160, MD5, and optionally OpenSSH Encrypt-then-MAC variants
Compression
none,zlib, andzlib@openssh.comConnection failures: Every Internet protocol begins with a TCP connection. Firewalls, endpoint security software, network ACLs, routing, proxies, or server-side policy may block the connection before SSH negotiation begins.
- Parameters:
domainName- thedomainNameargument (notnull)port- theportargument- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
connectThroughSsh
Connects to another SSH server through the already connected and authenticatedSshobject inssh.hostnameandportidentify the destination host and port.application → first SSH server → destination SSH server
After this method succeeds, authenticate separately with the destination server by calling one of its
Authenticate*methods.The proxy properties,
,getClientIpAddress(), and socket options on the inner object apply to this connection. SOCKS takes precedence over HTTP proxy settings, using the same selection rules asgetClientPort().connect(String, int)The inner object’s
controls the timeout for establishing this connection.getConnectTimeoutMs()- Parameters:
ssh- thesshargument (notnull)hostname- thehostnameargument (notnull)port- theportargument- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
continueKeyboardAuth
Continues keyboard-interactive authentication by submitting the response inresponse. For a single prompt,responsemay be the response text. When the preceding information request contains multiple prompts, supply an XML response:<response> <response1>response to first prompt</response1> <response2>response to second prompt</response2> ... </response>
The returned XML has one of three forms: authentication success, authentication failure, or another information request containing additional prompts.
<success>success message</success> <error>error message</error> <infoRequest numPrompts="N"> <name>name</name> <instruction>instructions</instruction> <prompt1 echo="1_or_0">prompt text</prompt1> ... </infoRequest>
- Parameters:
response- theresponseargument (notnull)- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
disconnect
public void disconnect()Closes the current SSH transport. It is harmless to call when no connection exists and may be called repeatedly.After this method returns,
isgetIsConnected()false,isgetNumOpenChannels()0, and former channels are no longer open or enumerated. However, bytes that were already buffered for a former channel can remain retrievable by its channel number after the disconnect. Retrieve the data and call, or allow the nextchannelRelease(int)call to clear retained old-channel data.connect(String, int)A local disconnect does not set
orgetDisconnectCode(); they remaingetDisconnectReason()0and an empty string.remains available, whilegetServerIdentifier()is cleared.getHostKeyFingerprint()The
Sshobject remains reusable. Writable configuration settings are not reset and remain in effect for subsequent calls to. Every new connection begins unauthenticated.connect(String, int) -
getAuthMethods
Queries a connected, unauthenticated SSH server for its advertised user-authentication methods. The result is a lowercase, comma-separated list without spaces, such aspublickey,password,keyboard-interactive.Connection side effect: Call this method after
and before authenticating. It intentionally disconnects after the query, so callconnect(String, int)Connectagain before authenticating. Calling it after successful authentication fails and also leaves the object disconnected.- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
getChannelExitStatus
public int getChannelExitStatus(int channelNum)Returns the remote process exit status received forchannelNum. Call this method only afterreturnschannelReceivedExitStatus(int)true.Retrieve the value immediately after the receive operation and before calling unrelated SSH methods, querying
, or releasing the channel. After the completed channel record is removed, a returned numericgetNumOpenChannels()0is not a valid substitute for checking method success.An exit status of
0conventionally indicates success on Unix-like systems; nonzero meanings are determined by the remote program and operating system. A nonzero exit status is not a Chilkat API failure and does not causeorsendReqExec(int, String)to fail.channelReceiveToClose(int)- Parameters:
channelNum- thechannelNumargument- Returns:
- the result (see
ChilkatObject.getLastMethodSuccess()where the description mentions failure)
-
getChannelNumber
public int getChannelNumber(int index)Returns the channel number at zero-based enumerationindexin the active channel collection. The index is an enumeration position, not a channel number. Useto determine the valid range fromgetNumOpenChannels()0throughNumOpenChannels - 1.Returns
-1whenindexis negative or otherwise out of range, including index0when the collection is empty. Channel numbers are opaque identifiers; do not assume they start at0, reset after reconnect, are sequential, or are reused predictably.The active collection can temporarily include a channel that was closed locally and is awaiting final remote-close processing. Former channels retained only for buffered-result retrieval after disconnect are not enumerated.
- Parameters:
index- theindexargument- Returns:
- the result (see
ChilkatObject.getLastMethodSuccess()where the description mentions failure)
-
getChannelType
Returns the type of the channel at zero-based enumerationindexin the active channel collection. The index is an enumeration position, not a channel number. Possible values includesession,x11,forwarded-tcpip, anddirect-tcpip.If
indexis negative or otherwise out of range, the string-returning method reports failure, returns null, and setsLastMethodSuccesstofalse. This includes index0whenisgetNumOpenChannels()0.The active collection can temporarily include a channel that was closed locally but is still awaiting final remote-close processing. Former channels retained only for buffered-result retrieval after disconnect are not enumerated.
- Parameters:
index- theindexargument- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
getHostKeyFP
Returns the active connection’s server host-key fingerprint.hashAlgspecifies the hash algorithm. Hash-algorithm names are case-insensitive. Common choices includeSHA256,SHA384,SHA512,SHA1,MD5, and the supported SHA-3 algorithms.The digest is Base64 encoded without trailing padding characters.
includeKeyTypecontrols whether the host-key type is included, andincludeHashNamecontrols whether the canonical hash name is included.includeKeyTypeincludeHashNameExample formattruetruessh-ed25519 SHA256:S1GreiGjlHBf1QlPPaHs2qxor4nDYl9bhFcPRN4FwF0truefalsessh-ed25519 S1GreiGjlHBf1QlPPaHs2qxor4nDYl9bhFcPRN4FwF0falsetrueSHA256:S1GreiGjlHBf1QlPPaHs2qxor4nDYl9bhFcPRN4FwF0falsefalseS1GreiGjlHBf1QlPPaHs2qxor4nDYl9bhFcPRN4FwF0An active SSH connection is required. The method fails when called before connecting or after disconnecting. For
MD5, this method still returns an unpadded Base64 digest; it does not return the colon-separated hexadecimal form used by.getHostKeyFingerprint()Important: If
hashAlgis not recognized, Chilkat falls back toSHA1. Applications should therefore pass a known algorithm name explicitly. Compare the returned fingerprint with a value obtained from a trusted source before sending credentials.- Parameters:
hashAlg- thehashAlgargument (notnull)includeKeyType- theincludeKeyTypeargumentincludeHashName- theincludeHashNameargument- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
getLastJsonData
Copies structured diagnostic information from the most recently called method into theJsonObjectinjson. Many methods do not produce additional JSON details; in those cases the object may contain little or no information.Authentication passwords and private-key passphrases are not included in this diagnostic JSON.
- Parameters:
json- thejsonargument (notnull)
-
getReceivedNumBytes
public int getReceivedNumBytes(int channelNum)Returns the number of bytes currently available in the normal receive buffer forchannelNum. It does not include bytes in the separate stderr buffer whenisgetStderrToStdout()false.Returns
-1when the channel number is invalid or its retained resources have been released. After a normalor abrupt transport loss, bytes received earlier can remain available and this method can still return their count even though the channel is no longer active or enumerable. A subsequentdisconnect()clears retained data from the previous session.connect(String, int)Buffered bytes can also remain after a timeout or cancellation. After normal channel completion, a later unrelated SSH operation can finalize and discard the completed channel record. Query and drain the buffer promptly.
Retrieve normal bytes with
,GetReceivedData,GetReceivedDataN, or a text getter. Retrieve separate stderr withGetReceivedBdorGetReceivedStderr.getReceivedStderrText(int, String)- Parameters:
channelNum- thechannelNumargument- Returns:
- the result (see
ChilkatObject.getLastMethodSuccess()where the description mentions failure)
-
getReceivedSb
Decodes and appends tosball text currently accumulated in the normal receive buffer forchannelNum, usingcharset. The receive buffer is cleared after the text is returned.For a valid retained channel with no buffered data, an empty string is returned successfully. For an invalid or no-longer-retained channel, the string-returning API reports failure. After channel completion, retrieve text immediately before unrelated SSH operations can discard the completed channel record.
When
isgetStripColorCodes()true, ANSI SGR color/style sequences are removed from the returned normal text. Other terminal-control sequences can remain.See Supported Charsets.
- Parameters:
channelNum- thechannelNumargumentcharset- thecharsetargument (notnull)sb- thesbargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
getReceivedStderrText
Decodes and returns all text currently accumulated in the separate stderr buffer forchannelNum, usingcharset. The stderr buffer is cleared after the text is returned.For a valid retained channel with no separate stderr, an empty string is returned successfully. For an invalid or no-longer-retained channel, the string-returning API reports failure. Retrieve stderr immediately after completion, before another SSH operation can discard the completed channel record.
is not applied to stderr text. Text getters do not retain an incomplete multibyte sequence for a later call; use raw bytes and a stateful application decoder for streaming multibyte data.getStripColorCodes()See Supported Charsets.
- Parameters:
channelNum- thechannelNumargumentcharset- thecharsetargument (notnull)- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
getReceivedText
Decodes and returns all text currently accumulated in the normal receive buffer forchannelNum, usingcharset. The receive buffer is cleared after the text is returned.For a valid retained channel with no buffered data, an empty string is returned successfully. For an invalid or no-longer-retained channel, the string-returning API reports failure. After channel completion, retrieve text immediately before unrelated SSH operations can discard the completed channel record.
When
isgetStripColorCodes()true, ANSI SGR color/style sequences are removed from the returned normal text. Other terminal-control sequences can remain.See Supported Charsets.
- Parameters:
channelNum- thechannelNumargumentcharset- thecharsetargument (notnull)- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
getReceivedTextS
Decodes text in the normal receive buffer forchannelNumand performs a literal, case-sensitive search forsubstrusingcharset.If found, the method returns and removes everything through and including the first occurrence. If not found, it returns an empty string successfully and leaves the buffer unchanged. An empty
substris invalid and causes failure without consuming the buffer.When
isgetStripColorCodes()true, SGR sequences are removed for both the substring search and the returned value. The method consumes the corresponding original raw bytes, including the stripped escape sequences.As with other destructive text getters, incomplete multibyte sequences are not retained as decoder state for a later call. Retrieve completed-channel text before unrelated SSH operations can remove the retained channel record.
- Parameters:
channelNum- thechannelNumargumentsubstr- thesubstrargument (notnull)charset- thecharsetargument (notnull)- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
openCustomChannel
Requests a custom SSH channel whose application-defined channel type is supplied inchannelType. The SSH server must implement that channel type. On success, returns the channel number used by the normal channel send, receive, EOF, CLOSE, and release methods.Returns
-1if the server rejects the channel. In that case,andgetChannelOpenFailCode()contain the server-provided failure information. The underlying SSH connection normally remains open,getChannelOpenFailReason()remainscheckConnection()true, and other channels can be opened and used afterward.A channel-open rejection does not set
orgetDisconnectCode()unless the server also sends an SSHgetDisconnectReason()DISCONNECT. Object-level configuration settings are unchanged.- Parameters:
channelType- thechannelTypeargument (notnull)- Returns:
- the result (see
ChilkatObject.getLastMethodSuccess()where the description mentions failure)
-
openDirectTcpIpChannel
Opens adirect-tcpipchannel through the SSH server totargetHostnameandtargetPort. The target name is sent to and resolved by the SSH server, not by the client computer. It must therefore be resolvable and reachable from the server's network environment. A numeric IPv4 address may be supplied to avoid remote DNS-name resolution.Each successful call creates one independent raw TCP byte stream. Multiple channels to the same target may be open concurrently. Bytes sent with
ChannelSend*methods are forwarded to the target, and bytes returned by the target are read withChannelRead*orChannelReceive*methods. For example, when the target is an SSH server, its SSH identification line is received as ordinary channel data. The channel is enumerated with typedirect-tcpip.Returns the new channel number on success, or
-1if the SSH server rejects or cannot establish the target connection. On server rejection, inspectandgetChannelOpenFailCode(). Name-resolution and target-connection failures normally leave the underlying SSH connection open.getChannelOpenFailReason()- Parameters:
targetHostname- thetargetHostnameargument (notnull)targetPort- thetargetPortargument- Returns:
- the result (see
ChilkatObject.getLastMethodSuccess()where the description mentions failure)
-
openSessionChannel
public int openSessionChannel()Opens a new SSH session channel. The SSH transport must already be connected and user authentication must have completed successfully. Calling this method beforeor before authentication returnsconnect(String, int)-1. A failure caused by missing authentication does not by itself close the SSH transport.Opening a session channel does not start a shell, execute a command, or start a subsystem. After opening the channel, send the appropriate session request.
1. Connect 2. Authenticate 3. OpenSessionChannel 4. Optionally send preparatory requests such as SendReqPty or SendReqSetEnv 5. Send one primary request: SendReqExec, SendReqShell, or SendReqSubsystem
Returns an opaque channel number on success, or
-1on failure. Do not assume channel numbers start at0, are sequential, or are reused in a predictable way.- Returns:
- the result (see
ChilkatObject.getLastMethodSuccess()where the description mentions failure)
-
peekReceivedText
Returns the text currently buffered in the normal receive buffer forchannelNum, decoded usingcharset, without removing any bytes.For a valid empty buffer, it returns an empty string successfully.
is not applied; terminal escape sequences are returned as buffered. Because the operation is nondestructive, it is useful for checking whether a complete multibyte sequence or logical delimiter has arrived before calling a destructive text getter.getStripColorCodes()- Parameters:
channelNum- thechannelNumargumentcharset- thecharsetargument (notnull)- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
quickCmdCheck
public int quickCmdCheck(int pollTimeoutMs)Waits up topollTimeoutMsmilliseconds for any command previously started byto complete. A value ofquickCmdSend(String)0performs a nonblocking check. Manually opened exec channels are not returned by this method.Return value Meaning
>= 0The channel number of a completed quick command. Each completed channel is returned only once.-1Pending quick commands exist, but none completed before the timeout.-2No quick commands remain to be checked, or an error occurred such as loss of the SSH connection. ExamineLastErrorTextand the connection state when the distinction matters.After a channel number is returned, retrieve its stdout, stderr, and exit status with the normal channel methods. The channel is not returned again on the next check, even before
is called.channelRelease(int)- Parameters:
pollTimeoutMs- thepollTimeoutMsargument- Returns:
- the result (see
ChilkatObject.getLastMethodSuccess()where the description mentions failure)
-
quickCmdSend
Starts a remote command and immediately returns its channel number, allowing multiple commands to run concurrently on the same authenticated SSH connection. Internally, this method opens a session channel and sends an exec request.commandis encoded according to. The returned channel is visible throughgetReqExecCharset(),getNumOpenChannels(), andgetChannelNumber(int), and remains owned by the application. UsegetChannelType(int)to detect completion, retrieve output and exit status with the normal channel methods, and then callquickCmdCheck(int). ReturnschannelRelease(int)-1on failure.- Parameters:
command- thecommandargument (notnull)- Returns:
- the result (see
ChilkatObject.getLastMethodSuccess()where the description mentions failure)
-
quickCommand
Executes one noninteractive remote command and returns the stdout collected as text. Internally, this method opens a session channel, sends an exec request, receives the command output through EOF, and decodes the stdout usingcharset.controls the encoding used to sendgetReqExecCharset()command.The final SSH channel
CLOSEcan still be pending when this method returns. The internal channel may therefore remain temporarily visible in, often with EOF already received but CLOSE not yet processed. Simply sleeping does not process pending SSH messages. A later SSH operation, such asgetNumOpenChannels()or anotherwaitForChannelMessage(int)QuickCommand, processes the final close and removes the previous channel.Remote exit status is not reflected in the return value: A command that exits nonzero may still return its stdout normally. An empty string can mean a successful command produced no stdout, or that a failed command wrote only to stderr. When
isgetStderrToStdout()false, separately received stderr is not included in the returned text. Exit status may or may not have arrived at the instant this method returns.Use
/quickCmdSend(String)or the explicit channel workflow when the application must reliably inspect stderr, provide stdin, or obtain the remote exit status. Do not depend on the temporary internal channel created by this convenience method.quickCmdCheck(int)- Parameters:
command- thecommandargument (notnull)charset- thecharsetargument (notnull)- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
quickShell
public int quickShell()Starts a remote shell using the simplified sequenceOpenSessionChannel→SendReqPty→SendReqShell. The default PTY size is 80 columns by 24 rows. Returns the open shell channel number on success, or-1on failure.The method returns after the shell request is accepted; it does not wait for or consume the initial login text or shell prompt. Use the returned channel with the normal send and receive methods, then allow the shell to close and call
after retrieving the required output and exit information.channelRelease(int)- Returns:
- the result (see
ChilkatObject.getLastMethodSuccess()where the description mentions failure)
-
reKey
public void reKey()Initiates SSH key re-exchange and waits for it to complete. Either client or server may initiate rekeying at any time.RFC 4253 recommends changing keys after approximately one gigabyte of transferred data or one hour of connection time, whichever occurs first. In normal use, servers initiate rekeying as needed and Chilkat handles it transparently.
- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
sendIgnore
public void sendIgnore()Sends an SSHIGNOREmessage. The server does not reply, but a successful send helps verify that the connection is still writable. No channel is required.- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
sendReqExec
Requests execution ofcommandLineon the session channel identified bychannelNum. The command text is sent using.getReqExecCharset()Request acceptance is not command success: A
truereturn means the SSH server accepted theexecrequest. The remote command can still fail, be missing, or exit with a nonzero status. Receive the channel to completion, then useandchannelReceivedExitStatus(int)to determine the remote process result.getChannelExitStatus(int)An exec channel is used for one command. Open a new session channel for each independent command. A second exec request on the same channel is normally rejected, while the first command continues running.
After the request is accepted, data sent with
orChannelSendDatabecomes the command’s standard input. CallchannelSendString(int, String, String)when no more input will be sent; stdout and stderr may still be received afterward.channelSendEof(int)- Parameters:
channelNum- thechannelNumargumentcommandLine- thecommandLineargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
sendReqPty
public void sendReqPty(int channelNum, String termType, int widthInChars, int heightInChars, int widthInPixels, int heightInPixels)Recommendation for automation: Do not request a pseudo-terminal unless the remote command or application specifically requires terminal behavior. Most automated SSH applications should operate without a PTY so that stdout and stderr remain clean, predictable, and easier to parse.Requests a pseudo-terminal for session channel
channelNum. The request must be sent before the primaryorsendReqExec(int, String)request.sendReqShell(int)The
termTypeargument identifies the terminal type and normally becomes the remote session'sTERMenvironment variable. The server and remote applications use this value to look up terminal capabilities in theirterminfoortermcapdatabase. The character and pixel dimensions describe the terminal window. Terminal modes previously added withare included in the request.setTtyMode(String, int)When no PTY is requested, the remote shell or command normally sees standard input and output as pipes rather than a terminal. Shells and programs commonly detect this using a check such as
isatty()and operate in non-interactive mode. In that mode, the server normally does not send a shell prompt, does not echo submitted commands, and avoids terminal-oriented output such as ANSI color and cursor-control sequences. Shell startup behavior can vary according to the remote shell and its configuration.Request type without a PTY Typical behavior
execThe server runs the requested command, returns its stdout and stderr, supplies EOF/CLOSE and usually an exit status, and then ends the channel. No command prompt is included.shellThe application may stream multiple newline-terminated commands through the channel as through a raw pipe. The server normally returns only command output, without prompts or echoed input.Without a prompt, an application must not wait for text such as
user@host:~$to determine when a command is finished. For anexecrequest, use the SSH protocol state: receive through channel EOF/CLOSE and inspect the exit status withandchannelReceivedExitStatus(int). For a long-lived shell channel, append a unique sentinel to each submitted command and receive until that sentinel is found.getChannelExitStatus(int)If a PTY is required for automation: Prefer
dumbfortermTypeunless the remote program genuinely needs a more capable terminal. Adumbterminal advertises little more than sequential text input and output, so well-behaved programs generally avoid color, cursor movement, screen clearing, and other terminal-control sequences. This is often the best choice for commands such assudoprompts or network-device CLIs that require a PTY but whose output still needs to be parsed.Terminal type When to use it
dumbRecommended when a PTY is mandatory but plain, sequential text is preferred. Full-screen programs such asvim,top, orhtopmay refuse to run or work poorly because cursor addressing is unavailable.xtermorxterm-256colorUse only when the client is prepared to handle a capable terminal stream containing cursor movement, screen-control sequences, text attributes, and possibly color. Chilkat does not emulate an xterm terminal.vt100orvt220Useful for compatibility with older terminal-oriented systems or devices. These still support cursor movement and control sequences.linuxorconsoleDescribe operating-system console terminals and should be used only when the application behaves like that console.screenortmuxDescribe terminal-multiplexer environments and are appropriate only when their capabilities are actually expected.The terminal type is a declaration of capabilities, not a filter applied by Chilkat. A remote application can ignore
TERM, force color, or emit escape sequences regardless of the selected type. If needed, also try sending environment requests such asNO_COLOR=1with. Servers commonly restrict client-supplied environment variables, so settingsendReqSetEnv(int, String, String)termTypetodumbin the PTY request is generally more reliable than attempting to setTERMseparately.A PTY changes remote-process behavior. Programs may display prompts, echo input, enable line buffering, execute interactive startup logic, emit terminal-control sequences, or alter formatting. Chilkat does not perform terminal emulation. A PTY also normally combines the remote process's stdout and stderr into one terminal stream, so
cannot preserve separate stderr on such a channel.getStderrToStdout()Only one PTY request per channel: Do not call this method a second time for the same channel. Some SSH servers treat a duplicate PTY request as a protocol error and disconnect the entire SSH session.
Recommended automation workflow: 1. OpenSessionChannel 2. Do not call SendReqPty unless terminal behavior is required 3. If a PTY is required but plain text is preferred, use termType = "dumb" 4. SendReqExec, or SendReqShell when multiple commands are required 5. Receive output and use SSH channel state, exit status, or a unique sentinel to detect completion
- Parameters:
channelNum- thechannelNumargumenttermType- thetermTypeargument (notnull)widthInChars- thewidthInCharsargumentheightInChars- theheightInCharsargumentwidthInPixels- thewidthInPixelsargumentheightInPixels- theheightInPixelsargument- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
sendReqSetEnv
Requests that the server set environment variablenametovaluefor the session channel identified bychannelNum. Send environment requests before the primaryexec,shell, orsubsystemrequest.Multiple variables may be requested. If the server accepts repeated requests for the same name, the later value is used. An empty value is allowed. The server controls which names are accepted; for example, an OpenSSH configuration can accept selected locale variables while rejecting arbitrary names.
A
truereturn means the server accepted this environment request. A rejected request returnsfalsebut normally leaves the channel and SSH connection usable, so the application can continue with the primary request. A request sent after the primary request has started is normally rejected.- Parameters:
channelNum- thechannelNumargumentname- thenameargument (notnull)value- thevalueargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
sendReqShell
public void sendReqShell(int channelNum)Starts a remote shell on the open session channel identified bychannelNum. A shell can be requested without a PTY when the server permits it. For an interactive terminal session, callfirst.sendReqPty(int, String, int, int, int, int)A
truereturn means the server accepted the shell request. This method does not wait for, detect, or remove a shell prompt. Login messages, prompts, command echo, and command output all arrive as ordinary channel data.Command boundaries are application-defined: SSH does not identify when an individual shell command finishes. Use a prompt pattern only when it is reliably known, or append a unique sentinel to each command and receive until that sentinel is found.
Send commands with
using the line ending expected by the remote shell or device. Unix-like shells normally accept LF; other systems may require CRLF or another terminator. Multiple commands may be sent sequentially until the shell exits or the channel closes.channelSendString(int, String, String)- Parameters:
channelNum- thechannelNumargument- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
sendReqSignal
Requests delivery ofsignalNameto the remote process running onchannelNum. Send the request after the exec process, shell, or subsystem has started. Supported signal names are:ABRT ALRM FPE HUP ILL INT KILL PIPE QUIT SEGV TERM USR1 USR2
These are Unix-style signals and are effective only when supported by the SSH server, remote operating system, and target process. A
truereturn indicates that the SSH request succeeded; the process may handle, ignore, or otherwise respond to the signal according to remote behavior.- Parameters:
channelNum- thechannelNumargumentsignalName- thesignalNameargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
sendReqSubsystem
Requests the predefined subsystem named bysubsystemNameon session channelchannelNum. Atruereturn means the server accepted the subsystem request; subsequent protocol data is exchanged with the normal channel send and receive methods.If the server rejects the subsystem, this method returns
falseand the channel normally remains open and reusable for another primary request such as. Once a subsystem request is accepted, do not send ansendReqExec(int, String)exec,shell, or second subsystem request on that channel.For example, the SSH
sftpsubsystem can be started this way, but applications should normally use theSFtpclass instead of implementing the SFTP protocol directly over anSshchannel.- Parameters:
channelNum- thechannelNumargumentsubsystemName- thesubsystemNameargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
sendReqWindowChange
public void sendReqWindowChange(int channelNum, int widthInChars, int heightInRows, int pixWidth, int pixHeight)Notifies the server that the terminal dimensions changed for the PTY associated withchannelNum.widthInCharsandheightInRowsspecify the character dimensions;pixWidthandpixHeightspecify the pixel dimensions.This request may be sent after the PTY is allocated, either before or after starting the shell or exec process. The tested OpenSSH servers applied the new character dimensions to an active shell.
- Parameters:
channelNum- thechannelNumargumentwidthInChars- thewidthInCharsargumentheightInRows- theheightInRowsargumentpixWidth- thepixWidthargumentpixHeight- thepixHeightargument- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
sendReqX11Forwarding
public void sendReqX11Forwarding(int channelNum, boolean singleConnection, String authProt, String authCookie, int screenNum)Sends an SSH X11-forwarding request on the session channel inchannelNum.singleConnectioncontrols whether forwarding is limited to a single connection;authProtthroughscreenNumprovide the X11 authentication protocol, cookie, and screen number.This low-level method exposes the SSH connection-protocol request. The application is responsible for supplying appropriate X11 values and handling forwarded X11 channels.
- Parameters:
channelNum- thechannelNumargumentsingleConnection- thesingleConnectionargumentauthProt- theauthProtargument (notnull)authCookie- theauthCookieargument (notnull)screenNum- thescreenNumargument- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
sendReqXonXoff
public void sendReqXonXoff(int channelNum, boolean clientCanDo)Deprecated for practical use. This method should not be used.- Parameters:
channelNum- thechannelNumargumentclientCanDo- theclientCanDoargument- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
setAllowedAlgorithms
Applies an explicit allow-list of SSH negotiation algorithms supplied injson. Use this method beforewhen security policy or server compatibility requires precise control over accepted host-key, key-exchange, cipher, MAC, or compression algorithms.connect(String, int)- Parameters:
json- thejsonargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
setTtyMode
Adds or updates one TTY mode to be included in a laterrequest.sendReqPty(int, String, int, int, int, int)ttyNameis the mode name andttyValueis its integer value. Call this method beforeSendReqPty, once for each mode to set. For example,SetTtyMode("ECHO", 0)requests that command input not be echoed by the allocated terminal.Supported mode names include:
VINTR VQUIT VERASE VKILL VEOF VEOL VEOL2 VSTART VSTOP VSUSP VDSUSP VREPRINT VWERASE VLNEXT VFLUSH VSWTCH VSTATUS VDISCARD IGNPAR PARMRK INPCK ISTRIP INLCR IGNCR ICRNL IUCLC IXON IXANY IXOFF IMAXBEL ISIG ICANON XCASE ECHO ECHOE ECHOK ECHONL NOFLSH TOSTOP IEXTEN ECHOCTL ECHOKE PENDIN OPOST OLCUC ONLCR OCRNL ONOCR ONLRET CS7 CS8 PARENB PARODD TTY_OP_ISPEED TTY_OP_OSPEED
Most applications do not need to set TTY modes explicitly. Use
before a later PTY request when previously configured modes should no longer be included.clearTtyModes()- Parameters:
ttyName- thettyNameargument (notnull)ttyValue- thettyValueargument- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
startKeyboardAuth
Begins keyboard-interactive authentication for the login inlogin. The returned XML describes the server’s prompts and whether each response should be echoed.<infoRequest numPrompts="N"> <name>name</name> <instruction>instructions</instruction> <prompt1 echo="1_or_0">prompt text</prompt1> ... </infoRequest>
If authentication immediately succeeds or fails, the returned XML instead has one of these forms:
<success>success message</success> <error>error message</error>
Submit responses with
.continueKeyboardAuth(String)- Parameters:
login- theloginargument (notnull)- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
waitForChannelMessage
public int waitForChannelMessage(int pollTimeoutMs)Waits for the next SSH channel message on any channel. ThepollTimeoutMsargument controls this method:0: nonblocking check.> 0: wait up to the specified number of milliseconds.< 0: wait without a method-level timeout.
The explicit argument governs the wait; shorter values of
orgetReadTimeoutMs()do not shorten it.getIdleTimeoutMs()Return value Meaning
>= 0The channel number associated with the message that was processed.-1No channel message arrived before the timeout.-2Another error occurred, such as a lost connection.The method processes one pending channel message. Ordinary data is appended to the appropriate channel buffer, and control messages can update EOF, CLOSE, and exit-status state. It does not consume bytes already buffered for the application.
A channel is not returned again merely because unread bytes remain buffered, but it can be returned again for a later stderr, EOF, exit-status, or CLOSE message.
Drain available stdout and stderr promptly after a channel number is returned. A later wait or poll that processes final closure can remove the completed channel record and make its buffered data and status unavailable.
- Parameters:
pollTimeoutMs- thepollTimeoutMsargument- Returns:
- the result (see
ChilkatObject.getLastMethodSuccess()where the description mentions failure)
-
setProgressListener
Installs the listener that receives this object's progress events (abortCheck,percentDone,progressInfo) during its long-running methods; replaces any listener or lambda installed before;nullremoves it.- Parameters:
listener- the listener, ornull- Throws:
IllegalStateException- if called from inside one of this object's own callbacks
-
getProgressListener
Returns the installed listener, ornull.- Returns:
- the listener installed with
setProgressListener(ProgressListener)or one of theon...methods
-
onAbortCheck
Installs a listener whose only callback isabortCheck: called everyHeartbeatMsmilliseconds during a long-running method; returntrueto abort it. Replaces any listener installed before.- Parameters:
callback- the callback, ornullto remove the listener
-
onPercentDone
Installs a listener whose only callback ispercentDone: called with the completion percentage (0..100) as a long-running method progresses; returntrueto abort it. Replaces any listener installed before.- Parameters:
callback- the callback, ornullto remove the listener
-
onProgressInfo
Installs a listener whose only callback isprogressInfo: called with a name/value pair of progress information as a long-running method proceeds. Replaces any listener installed before.- Parameters:
callback- the callback, ornullto remove the listener
-