Class Ssh

All Implemented Interfaces:
AutoCloseable

public class Ssh extends ChilkatObject
<section class="ssh-summary">

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 Details

    • Ssh

      public Ssh()
      Creates a new Ssh object.
  • Method Details

    • getAbortCurrent

      public boolean getAbortCurrent()
      Set to true to 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 getDisconnectCode() or getDisconnectReason(), and object-level configuration settings remain unchanged. An aborted connect(String, int) leaves the object disconnected but reusable for a later connection attempt.

      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 AbortCurrent property
    • setAbortCurrent

      public void setAbortCurrent​(boolean value)
      Sets the AbortCurrent property; see getAbortCurrent().
      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), authenticatePwPk(String, String, SshKey), and their SecureString variants. The initial value is 0, and a successful authentication resets it to 0. A failed attempt sets one of the following values.

      Value Meaning

      1 Transport failure. The connection is unavailable, communication was lost, or a read operation failed or timed out. Calling an authentication method before connect(String, int) also produces this value.

      2 Invalid key for public-key authentication. For example, the SshKey is empty, public-only, malformed, unsupported, or otherwise unsuitable.

      3 No mutually supported authentication method was available.

      4 SSH authentication protocol error. An unexpected or invalid message was received.

      5 The password or private key was rejected by the server.

      6 The SSH session is already authenticated.

      7 The server requires a password change. See getPasswordChangeRequested().

      This property is not cleared by unrelated operations such as sendIgnore() or disconnect(). Read it immediately after an authentication method returns. If the server closes the connection because of an authentication-attempt limit, the result may be 1; inspect getDisconnectCode(), getDisconnectReason(), and LastErrorText.

      Returns:
      the value of the AuthFailReason property (read-only)
    • getCaretControl

      public boolean getCaretControl()
      Controls whether recognized caret notation is converted to ASCII control characters in strings passed to sendReqExec(int, String) and channelSendString(int, String, String). The default is 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 CaretControl property
    • setCaretControl

      public void setCaretControl​(boolean value)
      Sets the CaretControl property; see getCaretControl().
      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

      1 SSH_OPEN_ADMINISTRATIVELY_PROHIBITED

      2 SSH_OPEN_CONNECT_FAILED

      3 SSH_OPEN_UNKNOWN_CHANNEL_TYPE

      4 SSH_OPEN_RESOURCE_SHORTAGE

      The initial value is 0. A local failure, such as attempting to open a channel before connecting, can also leave this property at 0 because no SSH channel-open failure message was received. Read this property immediately after a channel-open method returns -1.

      Returns:
      the value of the ChannelOpenFailCode property (read-only)
    • getChannelOpenFailReason

      public String getChannelOpenFailReason()
      Contains the descriptive text associated with getChannelOpenFailCode() when 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.

      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 getChannelOpenFailCode() unchanged.

      Returns:
      the value of the ChannelOpenFailReason property (read-only)
    • getClientIdentifier

      public String getClientIdentifier()
      Specifies the SSH client-identification string sent when a connection is established. The default is SSH-2.0-Chilkat_ followed by the Chilkat version, for example SSH-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 ClientIdentifier property
    • setClientIdentifier

      public void setClientIdentifier​(String value)
      Sets the ClientIdentifier property; see getClientIdentifier().
      Parameters:
      value - the new value (not null)
    • getClientIpAddress

      public String 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, connectThroughSsh(Ssh, String, int), and multi-hop SSH connections.

      Returns:
      the value of the ClientIpAddress property
    • setClientIpAddress

      public void setClientIpAddress​(String value)
      Sets the ClientIpAddress property; see getClientIpAddress().
      Parameters:
      value - the new value (not null)
    • getClientPort

      public int getClientPort()
      This property is normally left at its default value of 0. 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, connectThroughSsh(Ssh, String, int), and multi-hop SSH connections.

      Starting in Chilkat v11.6.0, assigned values must be in the range 0 through 65535. If a negative value or a value greater than 65535 is assigned, it is ignored and the existing property value remains unchanged.

      Returns:
      the value of the ClientPort property
    • setClientPort

      public void setClientPort​(int value)
      Sets the ClientPort property; see getClientPort().
      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 is 30000 (30 seconds).

      A value of 0 removes the Chilkat-imposed connect timeout; in practice, the attempt ends when the operating system reports that the connection failed. Negative values are treated as 0.

      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 connectThroughSsh(Ssh, String, int). For ConnectThroughSsh, the inner Ssh object’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 ConnectTimeoutMs property
    • setConnectTimeoutMs

      public void setConnectTimeoutMs​(int value)
      Sets the ConnectTimeoutMs property; see getConnectTimeoutMs().
      Parameters:
      value - the new value
    • getDisconnectCode

      public int getDisconnectCode()
      Contains the reason code from the most recent SSH DISCONNECT message received from the server. The values are defined by RFC 4253.

      The initial value is 0. It also remains 0 after a normal local disconnect(), an ordinary TCP connection loss that did not include an SSH DISCONNECT message, 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 checkConnection(). A subsequent call to connect(String, int) clears the value to 0, whether that new attempt succeeds or fails.

      Code Symbolic name

      1 SSH_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT

      2 SSH_DISCONNECT_PROTOCOL_ERROR

      3 SSH_DISCONNECT_KEY_EXCHANGE_FAILED

      4 SSH_DISCONNECT_RESERVED

      5 SSH_DISCONNECT_MAC_ERROR

      6 SSH_DISCONNECT_COMPRESSION_ERROR

      7 SSH_DISCONNECT_SERVICE_NOT_AVAILABLE

      8 SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED

      9 SSH_DISCONNECT_HOST_KEY_NOT_VERIFIABLE

      10 SSH_DISCONNECT_CONNECTION_LOST

      11 SSH_DISCONNECT_BY_APPLICATION

      12 SSH_DISCONNECT_TOO_MANY_CONNECTIONS

      13 SSH_DISCONNECT_AUTH_CANCELLED_BY_USER

      14 SSH_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE

      15 SSH_DISCONNECT_ILLEGAL_USER_NAME

      Returns:
      the value of the DisconnectCode property (read-only)
    • getDisconnectReason

      public String getDisconnectReason()
      Contains the descriptive text sent with the most recent server SSH DISCONNECT message. See getDisconnectCode() for the corresponding RFC 4253 reason code.

      The initial value is an empty string. It remains empty after a normal local disconnect(), an ordinary TCP connection loss without an SSH DISCONNECT message, a failed connection attempt, authentication rejection, receive timeout, receive abort, or rejected channel-open request.

      When a server-sent SSH DISCONNECT is received, the text remains available after checkConnection(). A subsequent call to connect(String, int) clears it, whether the new attempt succeeds or fails. The returned string is empty rather than null when no reason is available.

      Returns:
      the value of the DisconnectReason property (read-only)
    • getEnableCompression

      public boolean getEnableCompression()
      Controls whether SSH compression may be negotiated. The default is true, 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 EnableCompression property
    • setEnableCompression

      public void setEnableCompression​(boolean value)
      Sets the EnableCompression property; see getEnableCompression().
      Parameters:
      value - the new value
    • getEnableSecrets

      public boolean getEnableSecrets()
      Enables automatic resolution of secret specification strings from secure operating-system storage. The default is false.

      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(), authenticatePw(String, String), and authenticatePwPk(String, String, SshKey).

      Returns:
      the value of the EnableSecrets property
    • setEnableSecrets

      public void setEnableSecrets​(boolean value)
      Sets the EnableSecrets property; see getEnableSecrets().
      Parameters:
      value - the new value
    • getForceCipher

      public String 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.com

      aes128-ctr, aes192-ctr, aes256-ctr

      aes128-cbc, aes192-cbc, aes256-cbc

      aes128-gcm@openssh.com, aes256-gcm@openssh.com

      twofish128-cbc, twofish256-cbc

      blowfish-cbc, 3des-cbc

      arcfour128, arcfour256

      Cipher names must use the exact lowercase spelling shown above. If none of the specified ciphers is supported by the server, connect(String, int) fails.

      Returns:
      the value of the ForceCipher property
    • setForceCipher

      public void setForceCipher​(String value)
      Sets the ForceCipher property; see getForceCipher().
      Parameters:
      value - the new value (not null)
    • getHeartbeatMs

      public int getHeartbeatMs()
      Specifies the interval, in milliseconds, between AbortCheck event callbacks during operations that support progress events. The callback gives the application an opportunity to abort an operation before it completes.

      The default is 0, which disables periodic AbortCheck callbacks.

      Returns:
      the value of the HeartbeatMs property
    • setHeartbeatMs

      public void setHeartbeatMs​(int value)
      Sets the HeartbeatMs property; see getHeartbeatMs().
      Parameters:
      value - the new value
    • getHostKeyAlg

      public String getHostKeyAlg()
      Specifies the preferred host-key algorithm used during SSH connection establishment. The default is DSS; set it to RSA only when required for compatibility with a particular server.

      Normally this property should be left unchanged.

      Returns:
      the value of the HostKeyAlg property
    • setHostKeyAlg

      public void setHostKeyAlg​(String value)
      Sets the HostKeyAlg property; see getHostKeyAlg().
      Parameters:
      value - the new value (not null)
    • getHostKeyFingerprint

      public String 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 disconnect(), a server-sent SSH DISCONNECT, or a failed connection attempt.

      After an abrupt TCP loss, a previously obtained fingerprint can temporarily remain even when getIsConnected() is false. Therefore, a nonempty value is not proof that the connection is currently usable. Check IsConnected before 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 getHostKeyFP(String, boolean, boolean) with SHA256.

      Returns:
      the value of the HostKeyFingerprint property (read-only)
    • getHttpProxyAuthMethod

      public String 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.

      Basic Use HTTP Basic authentication.

      NTLM Use NTLM authentication.

      Basic and NTLM are the supported methods. Chilkat automatically handles a 407 Proxy Authentication Required response and performs the required authentication exchange.

      NTLMv2 is used unless NTLMv1 is explicitly selected by setting Global.DefaultNtlmVersion to 1.

      Returns:
      the value of the HttpProxyAuthMethod property
    • setHttpProxyAuthMethod

      public void setHttpProxyAuthMethod​(String value)
      Sets the HttpProxyAuthMethod property; see getHttpProxyAuthMethod().
      Parameters:
      value - the new value (not null)
    • getHttpProxyDomain

      public String 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 HttpProxyDomain property
    • setHttpProxyDomain

      public void setHttpProxyDomain​(String value)
      Sets the HttpProxyDomain property; see getHttpProxyDomain().
      Parameters:
      value - the new value (not null)
    • getHttpProxyHostname

      public String getHttpProxyHostname()
      Specifies the hostname or numeric IP address of an HTTP proxy.

      Chilkat uses the HTTP CONNECT method 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 getSocksVersion() is 0, this property is nonempty, and getHttpProxyPort() is nonzero. A configured SOCKS proxy takes precedence. These settings apply to both connect(String, int) and connectThroughSsh(Ssh, String, int).

      Returns:
      the value of the HttpProxyHostname property
    • setHttpProxyHostname

      public void setHttpProxyHostname​(String value)
      Sets the HttpProxyHostname property; see getHttpProxyHostname().
      Parameters:
      value - the new value (not null)
    • getHttpProxyPassword

      public String 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 HttpProxyPassword property
    • setHttpProxyPassword

      public void setHttpProxyPassword​(String value)
      Sets the HttpProxyPassword property; see getHttpProxyPassword().
      Parameters:
      value - the new value (not null)
    • getHttpProxyPort

      public int getHttpProxyPort()
      Specifies the HTTP proxy port.

      An HTTP proxy is used only when getSocksVersion() is 0, getHttpProxyHostname() is nonempty, and this property is nonzero. A configured SOCKS proxy takes precedence.

      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 HttpProxyPort property
    • setHttpProxyPort

      public void setHttpProxyPort​(int value)
      Sets the HttpProxyPort property; see getHttpProxyPort().
      Parameters:
      value - the new value
    • getHttpProxyUsername

      public String 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 HttpProxyUsername property
    • setHttpProxyUsername

      public void setHttpProxyUsername​(String value)
      Sets the HttpProxyUsername property; see getHttpProxyUsername().
      Parameters:
      value - the new value (not null)
    • getIdleTimeoutMs

      public int getIdleTimeoutMs()
      Specifies an inactivity interval, in milliseconds, for SSH receive waits that use this property. The default is 0, 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 channelPoll(int, int) and waitForChannelMessage(int), use that argument for the corresponding wait. In v11.6.0 testing, channelReadAndPoll(int, int) used IdleTimeoutMs for its initial read when getReadTimeoutMs() was 0.

      This property governs receiving. It is not a send-progress timeout.

      Returns:
      the value of the IdleTimeoutMs property
    • setIdleTimeoutMs

      public void setIdleTimeoutMs​(int value)
      Sets the IdleTimeoutMs property; see getIdleTimeoutMs().
      Parameters:
      value - the new value
    • getIsConnected

      public boolean getIsConnected()
      Returns true when Chilkat currently considers the SSH transport connected. It becomes true after connect(String, int) establishes the secure transport. It is false before connecting, after disconnect(), after a failed connection attempt, after a server-sent SSH 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 false before checkConnection() was called. However, true does 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 sendIgnore() and check its return value.

      After abrupt transport loss or a server protocol disconnect, retained per-channel state can be stale even though this property is false. Treat IsConnected = false as authoritative for network I/O. Bytes received before the loss can remain available in a retained channel buffer.

      Returns:
      the value of the IsConnected property (read-only)
    • getKeepSessionLog

      public boolean getKeepSessionLog()
      Controls whether SSH protocol traffic is accumulated in getSessionLog(). The default is 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 KeepSessionLog property
    • setKeepSessionLog

      public void setKeepSessionLog​(boolean value)
      Sets the KeepSessionLog property; see getKeepSessionLog().
      Parameters:
      value - the new value
    • getMaxPacketSize

      public int getMaxPacketSize()
      Specifies the maximum SSH channel packet size advertised in the SSH_MSG_CHANNEL_OPEN message. The default is 8192.

      For high-volume transfers, a value such as 32768 may improve performance.

      Returns:
      the value of the MaxPacketSize property
    • setMaxPacketSize

      public void setMaxPacketSize​(int value)
      Sets the MaxPacketSize property; see getMaxPacketSize().
      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 disconnect() or transport loss, this property returns 0 because 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 channelSendClose(int) can have channelIsOpen(int) return false while 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 channelReceiveToClose(int) or another completion receive returns, retrieve stdout, stderr, and exit status before reading NumOpenChannels; otherwise the completed channel record can be discarded.

      Use getChannelNumber(int) and getChannelType(int) with zero-based indexes from 0 through NumOpenChannels - 1. Do not assume every enumerated channel is still open for application I/O.

      Returns:
      the value of the NumOpenChannels property (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 by authenticatePw(String, String) and 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 PasswordChangeRequested property (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 PreferIpv6 property
    • setPreferIpv6

      public void setPreferIpv6​(boolean value)
      Sets the PreferIpv6 property; see getPreferIpv6().
      Parameters:
      value - the new value
    • getReadTimeoutMs

      public int getReadTimeoutMs()
      Specifies a receive timeout, in milliseconds, for SSH methods that use this property. The default is 0, meaning no ReadTimeoutMs limit.

      The exact scope is method-specific:

      Method Observed timeout scope

      channelRead(int) Limits the wait for channel input.

      channelReadAndPoll(int, int) Limits the initial wait when nonzero. After the first data arrives, pollTimeoutMs controls the additional quiet-period wait.

      channelReceiveToClose(int) Limits the receive operation while waiting for channel closure.

      channelReceiveUntilMatch(int, String, String, boolean) and channelReceiveUntilMatchN(int, StringArray, String, boolean) Limits the wait for a matching pattern.

      channelPoll(int, int) and waitForChannelMessage(int) Use their explicit pollTimeoutMs arguments 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 ReadTimeoutMs property
    • setReadTimeoutMs

      public void setReadTimeoutMs​(int value)
      Sets the ReadTimeoutMs property; see getReadTimeoutMs().
      Parameters:
      value - the new value
    • getReqExecCharset

      public String getReqExecCharset()
      Specifies the character encoding used for command text sent by sendReqExec(int, String), quickCommand(String, String), and quickCmdSend(String). The default is ANSI.

      On Windows, ANSI uses the Windows ANSI code page returned by GetACP, not the OEM code page. Its exact meaning on non-Windows platforms is environment-dependent. For portable behavior, specify an explicit charset such as utf-8 or windows-1252.

      This property applies to the command string itself. It does not override the explicit charset argument 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 ReqExecCharset property
    • setReqExecCharset

      public void setReqExecCharset​(String value)
      Sets the ReqExecCharset property; see getReqExecCharset().
      Parameters:
      value - the new value (not null)
    • getServerIdentifier

      public String 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 disconnect(), a server-sent SSH 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 ServerIdentifier property (read-only)
    • getSessionLog

      public String getSessionLog()
      Contains the in-memory SSH protocol log for the current or most recently completed successful session. Enable logging by setting getKeepSessionLog() to 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 connect(String, int) 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; inspect LastErrorText for 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 SessionLog property (read-only)
    • getSoRcvBuf

      public int getSoRcvBuf()
      Specifies the socket receive-buffer size. The default is 4194304 bytes. 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 SoRcvBuf property
    • setSoRcvBuf

      public void setSoRcvBuf​(int value)
      Sets the SoRcvBuf property; see getSoRcvBuf().
      Parameters:
      value - the new value
    • getSoSndBuf

      public int getSoSndBuf()
      Specifies the socket send-buffer size. The default is 262144 bytes. Normally this property should remain unchanged.

      When upload throughput is unexpectedly low, testing values such as 524288 or 1048576 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 SoSndBuf property
    • setSoSndBuf

      public void setSoSndBuf​(int value)
      Sets the SoSndBuf property; see getSoSndBuf().
      Parameters:
      value - the new value
    • getSocksHostname

      public String getSocksHostname()
      Specifies the SOCKS proxy hostname or IPv4 address. This property is used only when getSocksVersion() is 4 or 5. 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 SocksHostname property
    • setSocksHostname

      public void setSocksHostname​(String value)
      Sets the SocksHostname property; see getSocksHostname().
      Parameters:
      value - the new value (not null)
    • getSocksPassword

      public String 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 getSocksUsername() and this property empty to request no authentication. The connection fails if the proxy requires an unsupported authentication method.

      Returns:
      the value of the SocksPassword property
    • setSocksPassword

      public void setSocksPassword​(String value)
      Sets the SocksPassword property; see getSocksPassword().
      Parameters:
      value - the new value (not null)
    • getSocksPort

      public int getSocksPort()
      Specifies the SOCKS proxy port. The default is 1080. This property is used only when getSocksVersion() is 4 or 5.
      Returns:
      the value of the SocksPort property
    • setSocksPort

      public void setSocksPort​(int value)
      Sets the SocksPort property; see getSocksPort().
      Parameters:
      value - the new value
    • getSocksUsername

      public String getSocksUsername()
      Specifies the SOCKS username. For SOCKS4, it is sent as the SOCKS user ID. For SOCKS5, it is used with getSocksPassword() for username/password authentication.

      For SOCKS5, leave both properties empty to request no authentication.

      Returns:
      the value of the SocksUsername property
    • setSocksUsername

      public void setSocksUsername​(String value)
      Sets the SocksUsername property; see getSocksUsername().
      Parameters:
      value - the new value (not null)
    • getSocksVersion

      public int getSocksVersion()
      Selects whether and how a SOCKS proxy is used.

      Value Behavior

      0 Do not use a SOCKS proxy. This is the default. Chilkat may still use an HTTP proxy if both getHttpProxyHostname() and getHttpProxyPort() are set.

      4 Connect through a SOCKS4 proxy. SOCKS4a is not supported.

      5 Connect through a SOCKS5 proxy.

      Proxy selection: A SOCKS proxy takes precedence over an HTTP proxy. When this property is 4 or 5, Chilkat uses the configured SOCKS proxy. When it is 0, Chilkat uses an HTTP proxy only if HttpProxyHostname is nonempty and HttpProxyPort is nonzero. Otherwise, Chilkat connects directly to the SSH server.

      Assigning a value other than 4 or 5 sets the property to 0. These proxy settings apply to both connect(String, int) and connectThroughSsh(Ssh, String, int).

      Returns:
      the value of the SocksVersion property
    • setSocksVersion

      public void setSocksVersion​(int value)
      Sets the SocksVersion property; see getSocksVersion().
      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 is true.

      When true, retrieve combined stdout and stderr with GetReceivedData, GetReceivedDataN, getReceivedText(int, String), or getReceivedTextS(int, String, String). When false, retrieve SSH stderr separately with GetReceivedStderr or 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. getReceivedNumBytes(int) counts only the normal receive buffer.

      This setting also affects quickCommand(String, String). When 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 StderrToStdout property
    • setStderrToStdout

      public void setStderrToStdout​(boolean value)
      Sets the StderrToStdout property; see getStderrToStdout().
      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), getReceivedSb(int, String, StringBuilder) and getReceivedTextS(int, String, String). The default is 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 > and ESC ( 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 0x9B are 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, peekReceivedText(int, String), pattern matching in channelReceiveUntilMatch(int, String, String, boolean), or the string returned by 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 (its PROMPT_SP option).

      Returns:
      the value of the StripColorCodes property
    • setStripColorCodes

      public void setStripColorCodes​(boolean value)
      Sets the StripColorCodes property; see getStripColorCodes().
      Parameters:
      value - the new value
    • getTcpNoDelay

      public boolean getTcpNoDelay()
      Controls the TCP_NODELAY setting for the underlying TCP connection. The default is true, 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 TcpNoDelay property
    • setTcpNoDelay

      public void setTcpNoDelay​(boolean value)
      Sets the TcpNoDelay property; see getTcpNoDelay().
      Parameters:
      value - the new value
    • getUncommonOptions

      public String 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

      ForceUserAuthRsaSha1 Forces ssh-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-algs Removes hmac-sha1-96, hmac-sha1, hmac-md5, and hmac-ripemd160 from the offered MAC algorithms.

      ProtectFromVpn On Android, bypasses an installed or active VPN.

      +ssh-hmac-etm Re-enables Encrypt-then-MAC algorithms that are disabled by default as a Terrapin mitigation.

      +chacha20-poly1305@openssh.com Re-enables chacha20-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 UncommonOptions property
    • setUncommonOptions

      public void setUncommonOptions​(String value)
      Sets the UncommonOptions property; see getUncommonOptions().
      Parameters:
      value - the new value (not null)
    • getUserAuthBanner

      public String getUserAuthBanner()
      Contains a user-authentication banner received from the server during authentication. Check this property after startKeyboardAuth(String) or another authentication attempt and display it to the user when appropriate.

      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 UserAuthBanner property
    • setUserAuthBanner

      public void setUserAuthBanner​(String value)
      Sets the UserAuthBanner property; see getUserAuthBanner().
      Parameters:
      value - the new value (not null)
    • authenticatePk

      public void authenticatePk​(String username, SshKey privateKey)
      Authenticates an active, unauthenticated SSH connection using public-key authentication. username identifies the server account, and privateKey must contain the corresponding private key. The public key must already be authorized for that account on the server.

      An empty or public-only SshKey is rejected locally with getAuthFailReason() equal to 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 getIsConnected() is false.

      Calling this method before connect(String, int) fails with reason 1. Calling it after the session is already authenticated fails with reason 6.

      After a failure, inspect getAuthFailReason(), LastErrorText, and, if the connection was closed, getDisconnectReason().

      Parameters:
      username - the username argument (not null)
      privateKey - the privateKey argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • authenticatePw

      public void authenticatePw​(String login, String password)
      Authenticates an active, unauthenticated SSH connection using login and password.

      Call connect(String, int) first. Calling this method without a connection fails with getAuthFailReason() equal to 1. Calling it after the session is already authenticated fails with reason 6.

      If authentication fails and the server keeps the SSH connection open, getIsConnected() remains true and 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 when IsConnected is false.

      An authentication attempt clears or replaces getUserAuthBanner(). Object-level configuration settings remain unchanged.

      If the server requests a password change, see getPasswordChangeRequested().

      After a failure, inspect getAuthFailReason() and LastErrorText. getDisconnectCode() and getDisconnectReason() remain zero and empty unless the server actually sends an SSH DISCONNECT.

      Parameters:
      login - the login argument (not null)
      password - the password argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • authenticatePwPk

      public void authenticatePwPk​(String username, String password, SshKey privateKey)
      Authenticates with a server that requires both a password and a private key. username is the username, password is the password, and privateKey is the private key.

      Most servers require either password or public-key authentication rather than both. After a failure, inspect getAuthFailReason() and LastErrorText.

      Parameters:
      username - the username argument (not null)
      password - the password argument (not null)
      privateKey - the privateKey argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • authenticateSecPw

      public void authenticateSecPw​(SecureString login, SecureString password)
      Performs the same authentication as authenticatePw(String, String), but receives the login and password in SecureString objects.

      The connection-state, retry, timeout, and getAuthFailReason() behavior is the same as for AuthenticatePw.

      Parameters:
      login - the login argument (not null)
      password - the password argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • authenticateSecPwPk

      public void authenticateSecPwPk​(SecureString username, SecureString password, SshKey privateKey)
      Performs the same combined password/private-key authentication as authenticatePwPk(String, String, SshKey), but receives the username and password in SecureString objects.
      Parameters:
      username - the username argument (not null)
      password - the password argument (not null)
      privateKey - the privateKey argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • channelIsOpen

      public boolean channelIsOpen​(int channelNum)
      Returns true when channelNum identifies a channel that Chilkat currently considers open for application I/O; otherwise returns false. It returns false for invalid or nonexistent channel numbers, after a normal local disconnect(), after remote closure is processed, and immediately after channelSendClose(int) closes the channel locally.

      getNumOpenChannels() can temporarily continue counting a locally closed channel until final remote-close processing occurs.

      Connection loss: After abrupt transport loss or a server-sent SSH DISCONNECT, a retained channel record can temporarily cause this method to return true even though getIsConnected() is false. Treat IsConnected = false as authoritative. Buffered bytes from before the loss can still be retrievable.

      Parameters:
      channelNum - the channelNum argument
      Returns:
      the result; this method never throws ChilkatException
    • channelPoll

      public int channelPoll​(int channelNum, int pollTimeoutMs)
      Polls channelNum for incoming SSH channel messages, waiting at most pollTimeoutMs milliseconds. Pass 0 for a nonblocking poll. The explicit pollTimeoutMs controls this wait; shorter values of getReadTimeoutMs() or getIdleTimeoutMs() do not shorten it.

      Data received is appended to the normal receive buffer or separate stderr buffer according to getStderrToStdout().

      Return value Meaning

      -1 An error occurred. Inspect LastErrorText, getIsConnected(), and channelIsOpen(int).

      -2 No additional applicable channel message arrived before the applicable timeout. Previously buffered stdout or stderr can still be available.

      0 EOF or channel closure was processed. Buffered data can still remain and should be drained.

      > 0 The 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 getReceivedNumBytes(int), 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.

      Parameters:
      channelNum - the channelNum argument
      pollTimeoutMs - the pollTimeoutMs argument
      Returns:
      the result (see ChilkatObject.getLastMethodSuccess() where the description mentions failure)
    • channelRead

      public int channelRead​(int channelNum)
      Reads incoming SSH channel messages for channelNum. A nonzero getReadTimeoutMs() limits the wait for channel input. Received data is appended to the normal receive buffer or separate stderr buffer according to getStderrToStdout().

      Return value Meaning

      -1 An error occurred. Inspect LastErrorText, getIsConnected(), and channelIsOpen(int).

      -2 No additional applicable channel message arrived before the applicable timeout. Previously buffered stdout or stderr can still be available.

      0 EOF or channel closure was processed. Buffered data can still remain and should be drained.

      > 0 The 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 -2 rather 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 - the channelNum argument
      Returns:
      the result (see ChilkatObject.getLastMethodSuccess() where the description mentions failure)
    • channelReadAndPoll

      public int channelReadAndPoll​(int channelNum, int pollTimeoutMs)
      Reads channelNum in two phases:
      1. Waits for the first applicable channel message. A nonzero getReadTimeoutMs() limits this initial wait. When ReadTimeoutMs is 0, getIdleTimeoutMs() can provide the initial-read timeout.
      2. After data begins arriving, continues processing until no additional data arrives for pollTimeoutMs milliseconds.

      The second phase is governed by pollTimeoutMs; a shorter ReadTimeoutMs does 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

      -1 An error occurred. Inspect LastErrorText, getIsConnected(), and channelIsOpen(int).

      -2 No additional applicable channel message arrived before the applicable timeout. Previously buffered stdout or stderr can still be available.

      0 EOF or channel closure was processed. Buffered data can still remain and should be drained.

      > 0 The 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 0 or -2 while bytes remain buffered. Drain the normal and stderr buffers based on their actual contents, not solely on the method return value.

      Parameters:
      channelNum - the channelNum argument
      pollTimeoutMs - the pollTimeoutMs argument
      Returns:
      the result (see ChilkatObject.getLastMethodSuccess() where the description mentions failure)
    • channelReadAndPoll2

      public int channelReadAndPoll2​(int channelNum, int pollTimeoutMs, int maxNumBytes)
      Works like channelReadAndPoll(int, int), but also returns after newly processed data causes the total buffered channel data to reach or exceed maxNumBytes.

      maxNumBytes is 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 0 or 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

      -1 An error occurred. Inspect LastErrorText, getIsConnected(), and channelIsOpen(int).

      -2 No additional applicable channel message arrived before the timeout. Previously buffered stdout or stderr can still be available.

      0 EOF or channel closure was processed. Buffered data can still remain and should be drained.

      > 0 The 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 - the channelNum argument
      pollTimeoutMs - the pollTimeoutMs argument
      maxNumBytes - the maxNumBytes argument
      Returns:
      the result (see ChilkatObject.getLastMethodSuccess() where the description mentions failure)
    • channelReceiveToClose

      public void channelReceiveToClose​(int channelNum)
      Receives data on channelNum until the server sends and Chilkat processes channel CLOSE. 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 getStderrToStdout(). A nonzero getReadTimeoutMs() limits the receive operation. getIdleTimeoutMs() is not a simple stdout/stderr inactivity timer because any SSH communication can restart it.

      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 getDisconnectCode() or getDisconnectReason(). If the SSH transport is lost, the method fails and getIsConnected() becomes 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 getNumOpenChannels(). A later SSH operation can finalize and discard the completed channel record.

      A true return means the SSH receive operation completed. It does not mean the remote command exited successfully.

      Parameters:
      channelNum - the channelNum argument
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • channelReceiveUntilMatch

      public void channelReceiveUntilMatch​(int channelNum, String matchPattern, String charset, boolean caseSensitive)
      Receives text on channelNum until the accumulated text matches matchPattern. 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.

      charset specifies the character encoding, and caseSensitive controls comparison. The method can read beyond the matched text because an entire SSH packet may already be available.

      Matching considers stderr even when getStderrToStdout() is false. getStripColorCodes() is not applied before matching.

      A nonzero getReadTimeoutMs() limits the wait. getIdleTimeoutMs() is not a substitute for this limit because unrelated SSH traffic can restart the inactivity interval.

      Usage notes:

      • Use distinctive literal sentinels when exact command boundaries are required.
      • After success, getReceivedTextS(int, String, String) can remove and return text through a known literal terminator.
      • Avoid an empty matchPattern; it does not define a useful boundary.
      Parameters:
      channelNum - the channelNum argument
      matchPattern - the matchPattern argument (not null)
      charset - the charset argument (not null)
      caseSensitive - the caseSensitive argument
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • channelReceiveUntilMatchN

      public void channelReceiveUntilMatchN​(int channelNum, StringArray matchPatterns, String charset, boolean caseSensitive)
      Works like channelReceiveUntilMatch(int, String, String, boolean), but returns when any pattern in matchPatterns is 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 getLastJsonData(JsonObject) does not identify it. After success, inspect the buffered text or use distinct nonoverlapping sentinels that the application can identify reliably.

      The same pattern grammar, stderr behavior, and getReadTimeoutMs() behavior described for ChannelReceiveUntilMatch apply.

      Parameters:
      channelNum - the channelNum argument
      matchPatterns - the matchPatterns argument (not null)
      charset - the charset argument (not null)
      caseSensitive - the caseSensitive argument
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • channelReceivedClose

      public boolean channelReceivedClose​(int channelNum)
      Returns true if an SSH CLOSE message has been received for channelNum. Remote CLOSE is distinct from EOF and closes the channel in both directions. When it is processed, channelIsOpen(int) becomes false and the channel is normally removed from getNumOpenChannels().

      Returns false for an invalid, released, locally disconnected, or no-longer-retained channel number. A transport can be lost without receiving a channel CLOSE; check getIsConnected() separately.

      Retrieve buffered output, stderr, and exit status promptly after the receive method completes and before calling channelRelease(int).

      Parameters:
      channelNum - the channelNum argument
      Returns:
      the result; this method never throws ChilkatException
    • channelReceivedEof

      public boolean channelReceivedEof​(int channelNum)
      Returns true if an SSH EOF message has been received for channelNum. 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 is true, channelReceivedClose(int) is false, and the channel can remain open and counted by getNumOpenChannels(). Exit status and CLOSE can arrive later.

      Returns false for an invalid, released, disconnected, or no-longer-retained channel number. After transport failure, channel flags can be stale or unavailable; check getIsConnected() first.

      Parameters:
      channelNum - the channelNum argument
      Returns:
      the result; this method never throws ChilkatException
    • channelReceivedExitStatus

      public boolean channelReceivedExitStatus​(int channelNum)
      Returns true if the server supplied an exit-status value for channelNum. When true, 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 false for 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 - the channelNum argument
      Returns:
      the result; this method never throws ChilkatException
    • channelRelease

      public void channelRelease​(int channelNum)
      Releases Chilkat’s retained local resources for channelNum after 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 disconnect() to discard buffered data retained for a former channel. After release, methods such as getReceivedNumBytes(int) report that the channel is unavailable.

      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 - the channelNum argument
    • channelSendClose

      public void channelSendClose​(int channelNum)
      Sends an SSH CLOSE message for channelNum and 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, channelIsOpen(int) returns false, but getNumOpenChannels() can 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.

      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 - the channelNum argument
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • channelSendEof

      public void channelSendEof​(int channelNum)
      Sends an SSH EOF message on channelNum. 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 ChannelSendData or channelSendString(int, String, String) again for that channel. A later send call can return true even though the data is not delivered to the remote process. Repeated calls to ChannelSendEof are 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 - the channelNum argument
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • channelSendString

      public void channelSendString​(int channelNum, String textData, String charset)
      Encodes textData using charset, then sends the resulting bytes on channelNum. No line ending or terminator is added automatically.

      An empty string is valid and sends zero bytes. When getCaretControl() is true, recognized caret sequences are translated to control characters before sending.

      On Windows, ANSI uses the Windows ANSI code page returned by GetACP, not the OEM code page. Its meaning on other platforms is environment-dependent. Use an explicit charset such as utf-8 or windows-1252 for 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 channelSendEof(int). A successful return after EOF does not guarantee that the text was delivered.

      See Supported Charsets.

      Parameters:
      channelNum - the channelNum argument
      textData - the textData argument (not null)
      charset - the charset argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • checkConnection

      public boolean checkConnection()
      Returns true when the underlying SSH transport currently appears connected, and false when 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 getIsConnected(). It should not be treated as an end-to-end SSH round trip or proof that the remote server is responsive. Use sendIgnore() when an active SSH exchange is required.

      This method does not authenticate the session. A failed authentication, receive timeout, receive abort, or rejected channel-open request can leave it returning true because those failures do not necessarily close the transport.

      A false result can simply mean that no connection exists. The method does not necessarily replace LastErrorText, so an existing error string may describe an earlier operation.

      Returns true if the underlying TCP socket does not currently appear to be closed, or false if the connection is known to be closed or invalid.

      Unlike getIsConnected(), which reports the connection state already known by the Ssh object, this method performs an additional non-consuming check of the socket. It calls the operating system's recv function with MSG_PEEK to 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 true when the network path is silently broken but the operating system has not yet detected the failure. Use sendIgnore() when an active SSH round trip is required.

      A receive timeout, aborted operation, authentication failure, or rejected channel request does not necessarily close the socket. In those cases, CheckConnection may continue to return true.

      A false result can simply mean that no connection exists. This method may not replace LastErrorText when 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 setTtyMode(String, int). The next sendReqPty(int, String, int, int, int, int) request will not include those cleared modes.
    • connect

      public void connect​(String domainName, int port)
      Establishes an SSH connection to domainName on the TCP port specified by port. The domainName may be a DNS hostname or a numeric IPv4 or IPv6 address. A null or empty domainName is treated as a zero-length hostname and causes the call to fail.

      Proxy selection: If getSocksVersion() is 4 or 5, Chilkat connects through the configured SOCKS proxy. Otherwise, if getHttpProxyHostname() is nonempty and getHttpProxyPort() is nonzero, Chilkat connects through the HTTP proxy. If neither condition applies, Chilkat connects directly to the SSH server.

      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), authenticatePwPk(String, String, SshKey), or 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 Ssh object may be reused after disconnect(), connection refusal, connect timeout, connect abort, server protocol disconnect, or abrupt transport loss. A failed call leaves getIsConnected() equal to 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-dss

      Key exchange curve25519-sha256, curve25519-sha256@libssh.org, NIST ECDH, DH group 1/14/16/18, and group-exchange SHA-1/SHA-256

      Ciphers AES CTR/CBC/GCM, Twofish CBC, Blowfish CBC, and optionally chacha20-poly1305@openssh.com

      MAC SHA-2, SHA-1, RIPEMD-160, MD5, and optionally OpenSSH Encrypt-then-MAC variants

      Compression none, zlib, and zlib@openssh.com

      Connection 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 - the domainName argument (not null)
      port - the port argument
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • connectThroughSsh

      public void connectThroughSsh​(Ssh ssh, String hostname, int port)
      Connects to another SSH server through the already connected and authenticated Ssh object in ssh. hostname and port identify 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(), getClientPort(), and socket options on the inner object apply to this connection. SOCKS takes precedence over HTTP proxy settings, using the same selection rules as connect(String, int).

      The inner object’s getConnectTimeoutMs() controls the timeout for establishing this connection.

      Parameters:
      ssh - the ssh argument (not null)
      hostname - the hostname argument (not null)
      port - the port argument
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • continueKeyboardAuth

      public String continueKeyboardAuth​(String response)
      Continues keyboard-interactive authentication by submitting the response in response. For a single prompt, response may 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 - the response argument (not null)
      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, getIsConnected() is false, getNumOpenChannels() is 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 channelRelease(int), or allow the next connect(String, int) call to clear retained old-channel data.

      A local disconnect does not set getDisconnectCode() or getDisconnectReason(); they remain 0 and an empty string. getServerIdentifier() remains available, while getHostKeyFingerprint() is cleared.

      The Ssh object remains reusable. Writable configuration settings are not reset and remain in effect for subsequent calls to connect(String, int). Every new connection begins unauthenticated.

    • getAuthMethods

      public String getAuthMethods()
      Queries a connected, unauthenticated SSH server for its advertised user-authentication methods. The result is a lowercase, comma-separated list without spaces, such as publickey,password,keyboard-interactive.

      Connection side effect: Call this method after connect(String, int) and before authenticating. It intentionally disconnects after the query, so call Connect again 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 for channelNum. Call this method only after channelReceivedExitStatus(int) returns true.

      Retrieve the value immediately after the receive operation and before calling unrelated SSH methods, querying getNumOpenChannels(), or releasing the channel. After the completed channel record is removed, a returned numeric 0 is not a valid substitute for checking method success.

      An exit status of 0 conventionally 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 cause sendReqExec(int, String) or channelReceiveToClose(int) to fail.

      Parameters:
      channelNum - the channelNum argument
      Returns:
      the result (see ChilkatObject.getLastMethodSuccess() where the description mentions failure)
    • getChannelNumber

      public int getChannelNumber​(int index)
      Returns the channel number at zero-based enumeration index in the active channel collection. The index is an enumeration position, not a channel number. Use getNumOpenChannels() to determine the valid range from 0 through NumOpenChannels - 1.

      Returns -1 when index is negative or otherwise out of range, including index 0 when the collection is empty. Channel numbers are opaque identifiers; do not assume they start at 0, 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 - the index argument
      Returns:
      the result (see ChilkatObject.getLastMethodSuccess() where the description mentions failure)
    • getChannelType

      public String getChannelType​(int index)
      Returns the type of the channel at zero-based enumeration index in the active channel collection. The index is an enumeration position, not a channel number. Possible values include session, x11, forwarded-tcpip, and direct-tcpip.

      If index is negative or otherwise out of range, the string-returning method reports failure, returns null, and sets LastMethodSuccess to false. This includes index 0 when getNumOpenChannels() is 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 - the index argument
      Returns:
      the result (never null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • getHostKeyFP

      public String getHostKeyFP​(String hashAlg, boolean includeKeyType, boolean includeHashName)
      Returns the active connection’s server host-key fingerprint. hashAlg specifies the hash algorithm. Hash-algorithm names are case-insensitive. Common choices include SHA256, SHA384, SHA512, SHA1, MD5, and the supported SHA-3 algorithms.

      The digest is Base64 encoded without trailing padding characters. includeKeyType controls whether the host-key type is included, and includeHashName controls whether the canonical hash name is included.

      includeKeyType includeHashName Example format

      true true ssh-ed25519 SHA256:S1GreiGjlHBf1QlPPaHs2qxor4nDYl9bhFcPRN4FwF0

      true false ssh-ed25519 S1GreiGjlHBf1QlPPaHs2qxor4nDYl9bhFcPRN4FwF0

      false true SHA256:S1GreiGjlHBf1QlPPaHs2qxor4nDYl9bhFcPRN4FwF0

      false false S1GreiGjlHBf1QlPPaHs2qxor4nDYl9bhFcPRN4FwF0

      An 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 hashAlg is not recognized, Chilkat falls back to SHA1. 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 - the hashAlg argument (not null)
      includeKeyType - the includeKeyType argument
      includeHashName - the includeHashName argument
      Returns:
      the result (never null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • getLastJsonData

      public void getLastJsonData​(JsonObject json)
      Copies structured diagnostic information from the most recently called method into the JsonObject in json. 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 - the json argument (not null)
    • getReceivedNumBytes

      public int getReceivedNumBytes​(int channelNum)
      Returns the number of bytes currently available in the normal receive buffer for channelNum. It does not include bytes in the separate stderr buffer when getStderrToStdout() is false.

      Returns -1 when the channel number is invalid or its retained resources have been released. After a normal disconnect() or 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 subsequent connect(String, int) clears retained data from the previous session.

      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, GetReceivedBd, or a text getter. Retrieve separate stderr with GetReceivedStderr or getReceivedStderrText(int, String).

      Parameters:
      channelNum - the channelNum argument
      Returns:
      the result (see ChilkatObject.getLastMethodSuccess() where the description mentions failure)
    • getReceivedSb

      public void getReceivedSb​(int channelNum, String charset, StringBuilder sb)
      Decodes and appends to sb all text currently accumulated in the normal receive buffer for channelNum, using charset. 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 getStripColorCodes() is true, ANSI SGR color/style sequences are removed from the returned normal text. Other terminal-control sequences can remain.

      See Supported Charsets.

      Parameters:
      channelNum - the channelNum argument
      charset - the charset argument (not null)
      sb - the sb argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • getReceivedStderrText

      public String getReceivedStderrText​(int channelNum, String charset)
      Decodes and returns all text currently accumulated in the separate stderr buffer for channelNum, using charset. 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.

      getStripColorCodes() 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.

      See Supported Charsets.

      Parameters:
      channelNum - the channelNum argument
      charset - the charset argument (not null)
      Returns:
      the result (never null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • getReceivedText

      public String getReceivedText​(int channelNum, String charset)
      Decodes and returns all text currently accumulated in the normal receive buffer for channelNum, using charset. 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 getStripColorCodes() is true, ANSI SGR color/style sequences are removed from the returned normal text. Other terminal-control sequences can remain.

      See Supported Charsets.

      Parameters:
      channelNum - the channelNum argument
      charset - the charset argument (not null)
      Returns:
      the result (never null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • getReceivedTextS

      public String getReceivedTextS​(int channelNum, String substr, String charset)
      Decodes text in the normal receive buffer for channelNum and performs a literal, case-sensitive search for substr using charset.

      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 substr is invalid and causes failure without consuming the buffer.

      When getStripColorCodes() is 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 - the channelNum argument
      substr - the substr argument (not null)
      charset - the charset argument (not null)
      Returns:
      the result (never null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • openCustomChannel

      public int openCustomChannel​(String channelType)
      Requests a custom SSH channel whose application-defined channel type is supplied in channelType. 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 -1 if the server rejects the channel. In that case, getChannelOpenFailCode() and getChannelOpenFailReason() contain the server-provided failure information. The underlying SSH connection normally remains open, checkConnection() remains true, and other channels can be opened and used afterward.

      A channel-open rejection does not set getDisconnectCode() or getDisconnectReason() unless the server also sends an SSH DISCONNECT. Object-level configuration settings are unchanged.

      Parameters:
      channelType - the channelType argument (not null)
      Returns:
      the result (see ChilkatObject.getLastMethodSuccess() where the description mentions failure)
    • openDirectTcpIpChannel

      public int openDirectTcpIpChannel​(String targetHostname, int targetPort)
      Opens a direct-tcpip channel through the SSH server to targetHostname and targetPort. 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 with ChannelRead* or ChannelReceive* 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 type direct-tcpip.

      Returns the new channel number on success, or -1 if the SSH server rejects or cannot establish the target connection. On server rejection, inspect getChannelOpenFailCode() and getChannelOpenFailReason(). Name-resolution and target-connection failures normally leave the underlying SSH connection open.

      Parameters:
      targetHostname - the targetHostname argument (not null)
      targetPort - the targetPort argument
      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 before connect(String, int) or before authentication returns -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 -1 on failure. Do not assume channel numbers start at 0, are sequential, or are reused in a predictable way.

      Returns:
      the result (see ChilkatObject.getLastMethodSuccess() where the description mentions failure)
    • peekReceivedText

      public String peekReceivedText​(int channelNum, String charset)
      Returns the text currently buffered in the normal receive buffer for channelNum, decoded using charset, without removing any bytes.

      For a valid empty buffer, it returns an empty string successfully. getStripColorCodes() 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.

      Parameters:
      channelNum - the channelNum argument
      charset - the charset argument (not null)
      Returns:
      the result (never null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • quickCmdCheck

      public int quickCmdCheck​(int pollTimeoutMs)
      Waits up to pollTimeoutMs milliseconds for any command previously started by quickCmdSend(String) to complete. A value of 0 performs a nonblocking check. Manually opened exec channels are not returned by this method.

      Return value Meaning

      >= 0 The channel number of a completed quick command. Each completed channel is returned only once.

      -1 Pending quick commands exist, but none completed before the timeout.

      -2 No quick commands remain to be checked, or an error occurred such as loss of the SSH connection. Examine LastErrorText and 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 channelRelease(int) is called.

      Parameters:
      pollTimeoutMs - the pollTimeoutMs argument
      Returns:
      the result (see ChilkatObject.getLastMethodSuccess() where the description mentions failure)
    • quickCmdSend

      public int quickCmdSend​(String command)
      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.

      command is encoded according to getReqExecCharset(). The returned channel is visible through getNumOpenChannels(), getChannelNumber(int), and getChannelType(int), and remains owned by the application. Use quickCmdCheck(int) to detect completion, retrieve output and exit status with the normal channel methods, and then call channelRelease(int). Returns -1 on failure.

      Parameters:
      command - the command argument (not null)
      Returns:
      the result (see ChilkatObject.getLastMethodSuccess() where the description mentions failure)
    • quickCommand

      public String quickCommand​(String command, String charset)
      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 using charset. getReqExecCharset() controls the encoding used to send command.

      The final SSH channel CLOSE can still be pending when this method returns. The internal channel may therefore remain temporarily visible in getNumOpenChannels(), often with EOF already received but CLOSE not yet processed. Simply sleeping does not process pending SSH messages. A later SSH operation, such as waitForChannelMessage(int) or another 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 getStderrToStdout() is 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)/quickCmdCheck(int) 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.

      Parameters:
      command - the command argument (not null)
      charset - the charset argument (not null)
      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 sequence OpenSessionChannel → SendReqPty → SendReqShell. The default PTY size is 80 columns by 24 rows. Returns the open shell channel number on success, or -1 on 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 channelRelease(int) after retrieving the required output and exit information.

      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 SSH IGNORE message. 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

      public void sendReqExec​(int channelNum, String commandLine)
      Requests execution of commandLine on the session channel identified by channelNum. The command text is sent using getReqExecCharset().

      Request acceptance is not command success: A true return means the SSH server accepted the exec request. The remote command can still fail, be missing, or exit with a nonzero status. Receive the channel to completion, then use channelReceivedExitStatus(int) and getChannelExitStatus(int) to determine the remote process result.

      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 ChannelSendData or channelSendString(int, String, String) becomes the command’s standard input. Call channelSendEof(int) when no more input will be sent; stdout and stderr may still be received afterward.

      Parameters:
      channelNum - the channelNum argument
      commandLine - the commandLine argument (not null)
      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 primary sendReqExec(int, String) or sendReqShell(int) request.

      The termType argument identifies the terminal type and normally becomes the remote session's TERM environment variable. The server and remote applications use this value to look up terminal capabilities in their terminfo or termcap database. The character and pixel dimensions describe the terminal window. Terminal modes previously added with setTtyMode(String, int) are included in the request.

      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

      exec The 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.

      shell The 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 an exec request, use the SSH protocol state: receive through channel EOF/CLOSE and inspect the exit status with channelReceivedExitStatus(int) and getChannelExitStatus(int). For a long-lived shell channel, append a unique sentinel to each submitted command and receive until that sentinel is found.

      If a PTY is required for automation: Prefer dumb for termType unless the remote program genuinely needs a more capable terminal. A dumb terminal 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 as sudo prompts or network-device CLIs that require a PTY but whose output still needs to be parsed.

      Terminal type When to use it

      dumb Recommended when a PTY is mandatory but plain, sequential text is preferred. Full-screen programs such as vim, top, or htop may refuse to run or work poorly because cursor addressing is unavailable.

      xterm or xterm-256color Use 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.

      vt100 or vt220 Useful for compatibility with older terminal-oriented systems or devices. These still support cursor movement and control sequences.

      linux or console Describe operating-system console terminals and should be used only when the application behaves like that console.

      screen or tmux Describe 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 as NO_COLOR=1 with sendReqSetEnv(int, String, String). Servers commonly restrict client-supplied environment variables, so setting termType to dumb in the PTY request is generally more reliable than attempting to set TERM separately.

      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 getStderrToStdout() cannot preserve separate stderr on such a channel.

      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 - the channelNum argument
      termType - the termType argument (not null)
      widthInChars - the widthInChars argument
      heightInChars - the heightInChars argument
      widthInPixels - the widthInPixels argument
      heightInPixels - the heightInPixels argument
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • sendReqSetEnv

      public void sendReqSetEnv​(int channelNum, String name, String value)
      Requests that the server set environment variable name to value for the session channel identified by channelNum. Send environment requests before the primary exec, shell, or subsystem request.

      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 true return means the server accepted this environment request. A rejected request returns false but 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 - the channelNum argument
      name - the name argument (not null)
      value - the value argument (not null)
      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 by channelNum. A shell can be requested without a PTY when the server permits it. For an interactive terminal session, call sendReqPty(int, String, int, int, int, int) first.

      A true return 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 channelSendString(int, String, String) 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.

      Parameters:
      channelNum - the channelNum argument
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • sendReqSignal

      public void sendReqSignal​(int channelNum, String signalName)
      Requests delivery of signalName to the remote process running on channelNum. 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 true return indicates that the SSH request succeeded; the process may handle, ignore, or otherwise respond to the signal according to remote behavior.

      Parameters:
      channelNum - the channelNum argument
      signalName - the signalName argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • sendReqSubsystem

      public void sendReqSubsystem​(int channelNum, String subsystemName)
      Requests the predefined subsystem named by subsystemName on session channel channelNum. A true return 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 false and the channel normally remains open and reusable for another primary request such as sendReqExec(int, String). Once a subsystem request is accepted, do not send an exec, shell, or second subsystem request on that channel.

      For example, the SSH sftp subsystem can be started this way, but applications should normally use the SFtp class instead of implementing the SFTP protocol directly over an Ssh channel.

      Parameters:
      channelNum - the channelNum argument
      subsystemName - the subsystemName argument (not null)
      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 with channelNum. widthInChars and heightInRows specify the character dimensions; pixWidth and pixHeight specify 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 - the channelNum argument
      widthInChars - the widthInChars argument
      heightInRows - the heightInRows argument
      pixWidth - the pixWidth argument
      pixHeight - the pixHeight argument
      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 in channelNum. singleConnection controls whether forwarding is limited to a single connection; authProt through screenNum provide 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 - the channelNum argument
      singleConnection - the singleConnection argument
      authProt - the authProt argument (not null)
      authCookie - the authCookie argument (not null)
      screenNum - the screenNum argument
      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 - the channelNum argument
      clientCanDo - the clientCanDo argument
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • setAllowedAlgorithms

      public void setAllowedAlgorithms​(JsonObject json)
      Applies an explicit allow-list of SSH negotiation algorithms supplied in json. Use this method before connect(String, int) when security policy or server compatibility requires precise control over accepted host-key, key-exchange, cipher, MAC, or compression algorithms.
      Parameters:
      json - the json argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • setTtyMode

      public void setTtyMode​(String ttyName, int ttyValue)
      Adds or updates one TTY mode to be included in a later sendReqPty(int, String, int, int, int, int) request. ttyName is the mode name and ttyValue is its integer value. Call this method before SendReqPty, 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 clearTtyModes() before a later PTY request when previously configured modes should no longer be included.

      Parameters:
      ttyName - the ttyName argument (not null)
      ttyValue - the ttyValue argument
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • startKeyboardAuth

      public String startKeyboardAuth​(String login)
      Begins keyboard-interactive authentication for the login in login. 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 - the login argument (not null)
      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. The pollTimeoutMs argument 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 getReadTimeoutMs() or getIdleTimeoutMs() do not shorten it.

      Return value Meaning

      >= 0 The channel number associated with the message that was processed.

      -1 No channel message arrived before the timeout.

      -2 Another 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 - the pollTimeoutMs argument
      Returns:
      the result (see ChilkatObject.getLastMethodSuccess() where the description mentions failure)
    • setProgressListener

      public void setProgressListener​(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; null removes it.
      Parameters:
      listener - the listener, or null
      Throws:
      IllegalStateException - if called from inside one of this object's own callbacks
    • getProgressListener

      public ProgressListener getProgressListener()
      Returns the installed listener, or null.
      Returns:
      the listener installed with setProgressListener(ProgressListener) or one of the on... methods
    • onAbortCheck

      public void onAbortCheck​(BooleanSupplier callback)
      Installs a listener whose only callback is abortCheck: called every HeartbeatMs milliseconds during a long-running method; return true to abort it. Replaces any listener installed before.
      Parameters:
      callback - the callback, or null to remove the listener
    • onPercentDone

      public void onPercentDone​(IntPredicate callback)
      Installs a listener whose only callback is percentDone: called with the completion percentage (0..100) as a long-running method progresses; return true to abort it. Replaces any listener installed before.
      Parameters:
      callback - the callback, or null to remove the listener
    • onProgressInfo

      public void onProgressInfo​(BiConsumer<String,​String> callback)
      Installs a listener whose only callback is progressInfo: called with a name/value pair of progress information as a long-running method proceeds. Replaces any listener installed before.
      Parameters:
      callback - the callback, or null to remove the listener