### ProxyCommand-style Connection with SSHJ Source: https://context7.com/hierynomus/sshj/llms.txt Connects to SSH servers by leveraging an external process for input/output, mimicking OpenSSH's `ProxyCommand`. This example demonstrates using `ssh` with the `-W` option via `ProcessBuilder` and SSHJ's `connectVia` method. ```java import net.schmizz.sshj.SSHClient; import net.schmizz.sshj.common.IOUtils; import net.schmizz.sshj.connection.channel.direct.Session; import net.schmizz.sshj.transport.verification.PromiscuousVerifier; import java.io.InputStream; import java.io.OutputStream; import java.util.concurrent.TimeUnit; // Use external SSH client as proxy (e.g., for AWS SSM) String jumpBox = "jump.example.com"; String targetBox = "internal.example.com"; ProcessBuilder pb = new ProcessBuilder("ssh", jumpBox, "-W", targetBox + ":22"); Process proc = pb.start(); InputStream recvStream = proc.getInputStream(); OutputStream xmitStream = proc.getOutputStream(); SSHClient ssh = new SSHClient(); ssh.addHostKeyVerifier(new PromiscuousVerifier()); ssh.connectVia(recvStream, xmitStream); try { ssh.authPublickey(System.getProperty("user.name")); Session session = ssh.startSession(); try { Session.Command cmd = session.exec("whoami"); System.out.println(IOUtils.readFully(cmd.getInputStream()).toString()); cmd.join(5, TimeUnit.SECONDS); } finally { session.close(); } } finally { ssh.disconnect(); ssh.close(); } ``` -------------------------------- ### Execute Remote Commands with SSHJ (Java) Source: https://context7.com/hierynomus/sshj/llms.txt Shows how to execute a remote command on an SSH server using SSHJ in Java. It demonstrates starting a session, executing a command, reading its standard output and error streams, and retrieving the exit status. Includes handling command timeouts. ```java import net.schmizz.sshj.SSHClient; import net.schmizz.sshj.common.IOUtils; import net.schmizz.sshj.connection.channel.direct.Session; import net.schmizz.sshj.connection.channel.direct.Session.Command; import java.util.concurrent.TimeUnit; SSHClient ssh = new SSHClient(); ssh.loadKnownHosts(); ssh.connect("localhost"); try { ssh.authPublickey(System.getProperty("user.name")); Session session = ssh.startSession(); try { // Execute command Command cmd = session.exec("ping -c 1 google.com"); // Read stdout String output = IOUtils.readFully(cmd.getInputStream()).toString(); System.out.println(output); // Wait for command to complete (max 5 seconds) cmd.join(5, TimeUnit.SECONDS); // Get exit status (call close() first to ensure status is available) System.out.println("Exit status: " + cmd.getExitStatus()); // Check for error output String errorOutput = IOUtils.readFully(cmd.getErrorStream()).toString(); if (!errorOutput.isEmpty()) { System.err.println("Errors: " + errorOutput); } } finally { session.close(); } } finally { ssh.disconnect(); } ``` -------------------------------- ### Start Interactive Shell Session with PTY Allocation (Java) Source: https://context7.com/hierynomus/sshj/llms.txt Initiates an interactive shell session with Pseudo-Terminal (PTY) allocation, essential for running interactive programs or sequential commands. It streams input/output between the local console and the remote shell. Requires SSHJ library. ```java import net.schmizz.sshj.SSHClient; import net.schmizz.sshj.common.StreamCopier; import net.schmizz.sshj.common.LoggerFactory; import net.schmizz.sshj.connection.channel.direct.Session; import net.schmizz.sshj.connection.channel.direct.Session.Shell; SSHClient ssh = new SSHClient(); ssh.loadKnownHosts(); ssh.connect("localhost"); try { ssh.authPublickey(System.getProperty("user.name")); Session session = ssh.startSession(); try { // Allocate a pseudo-terminal (required for interactive shells) session.allocateDefaultPTY(); // Or with custom settings: // session.allocatePTY("xterm", 80, 24, 640, 480, Collections.emptyMap()); // Start shell Shell shell = session.startShell(); // Copy shell output to System.out new StreamCopier(shell.getInputStream(), System.out, LoggerFactory.DEFAULT) .bufSize(shell.getLocalMaxPacketSize()) .spawn("stdout"); // Copy shell errors to System.err new StreamCopier(shell.getErrorStream(), System.err, LoggerFactory.DEFAULT) .bufSize(shell.getLocalMaxPacketSize()) .spawn("stderr"); // Copy System.in to shell (blocks until EOF/Ctrl+D) new StreamCopier(System.in, shell.getOutputStream(), LoggerFactory.DEFAULT) .bufSize(shell.getRemoteMaxPacketSize()) .copy(); } finally { session.close(); } } finally { ssh.disconnect(); } ``` -------------------------------- ### Remote Port Forwarding with SSHJ Source: https://context7.com/hierynomus/sshj/llms.txt Configures the SSH server to listen on a specified port and forward incoming connections to a local machine or a remote service. This example uses SSHJ's `RemotePortForwarder` and `SocketForwardingConnectListener`. ```java import net.schmizz.sshj.SSHClient; import net.schmizz.sshj.connection.channel.forwarded.RemotePortForwarder.Forward; import net.schmizz.sshj.connection.channel.forwarded.SocketForwardingConnectListener; import java.net.InetSocketAddress; SSHClient ssh = new SSHClient(); ssh.loadKnownHosts(); ssh.connect("localhost"); // Enable keep-alive to maintain the connection ssh.getConnection().getKeepAlive().setKeepAliveInterval(5); try { ssh.authPublickey(System.getProperty("user.name")); // Server listens on port 8080, forwards connections to google.com:80 ssh.getRemotePortForwarder().bind( new Forward(8080), // Remote port to listen on new SocketForwardingConnectListener(new InetSocketAddress("google.com", 80)) ); // Keep connection alive - waits until disconnected ssh.getTransport().join(); } finally { ssh.disconnect(); } ``` -------------------------------- ### Connect and Authenticate with SSHJ (Java) Source: https://context7.com/hierynomus/sshj/llms.txt Demonstrates how to establish an SSH connection using SSHClient in Java. It covers loading known hosts, connecting to a server, and performing public key or password authentication. It also shows how to skip host key verification (for testing) and verify by fingerprint. ```java import net.schmizz.sshj.SSHClient; import net.schmizz.sshj.transport.verification.PromiscuousVerifier; // Basic connection with known_hosts verification SSHClient ssh = new SSHClient(); try { ssh.loadKnownHosts(); // Load ~/.ssh/known_hosts ssh.connect("hostname"); // Public key authentication (uses ~/.ssh/id_rsa, id_dsa, id_ed25519, id_ecdsa) ssh.authPublickey(System.getProperty("user.name")); // ... perform operations ... } finally { ssh.disconnect(); } // Password authentication SSHClient ssh2 = new SSHClient(); try { ssh2.loadKnownHosts(); ssh2.connect("hostname"); ssh2.authPassword("username", "password"); // ... perform operations ... } finally { ssh2.disconnect(); } // Skip host key verification (for testing only - NOT recommended for production) SSHClient ssh3 = new SSHClient(); ssh3.addHostKeyVerifier(new PromiscuousVerifier()); ssh3.connect("hostname"); // Verify by fingerprint SSHClient ssh4 = new SSHClient(); ssh4.addHostKeyVerifier("SHA256:oQGbQTujGeNIgh0ONthcEpA/BHxtt3rcYY+NxXTxQjs="); ssh4.connect("hostname"); ``` -------------------------------- ### SFTP Directory and File Operations in Java Source: https://context7.com/hierynomus/sshj/llms.txt Demonstrates various SFTP operations including listing directories, creating/removing files and directories, renaming, changing permissions, and symbolic link management. Requires SSHClient and SFTPClient from the SSHJ library. ```java import net.schmizz.sshj.SSHClient; import net.schmizz.sshj.sftp.SFTPClient; import net.schmizz.sshj.sftp.RemoteResourceInfo; import net.schmizz.sshj.sftp.FileAttributes; import net.schmizz.sshj.sftp.OpenMode; import net.schmizz.sshj.sftp.RemoteFile; import java.util.EnumSet; import java.util.List; SSHClient ssh = new SSHClient(); ssh.loadKnownHosts(); ssh.connect("localhost"); try { ssh.authPublickey(System.getProperty("user.name")); SFTPClient sftp = ssh.newSFTPClient(); try { // List directory contents List files = sftp.ls("/home/user"); for (RemoteResourceInfo file : files) { System.out.println(file.getName() + " - " + file.getAttributes().getSize() + " bytes"); } // Create directory sftp.mkdir("/tmp/newdir"); // Create nested directories (like mkdir -p) sftp.mkdirs("/tmp/path/to/nested/dir"); // Remove file sftp.rm("/tmp/oldfile.txt"); // Remove directory sftp.rmdir("/tmp/emptydir"); // Rename/move file sftp.rename("/tmp/oldname.txt", "/tmp/newname.txt"); // Get file attributes FileAttributes attrs = sftp.stat("/tmp/file.txt"); System.out.println("Size: " + attrs.getSize()); System.out.println("UID: " + attrs.getUID()); System.out.println("Modified: " + attrs.getMtime()); // Change permissions (chmod) sftp.chmod("/tmp/script.sh", 0755); // Change owner sftp.chown("/tmp/file.txt", 1000); // Change group sftp.chgrp("/tmp/file.txt", 1000); // Create symbolic link sftp.symlink("/tmp/link", "/tmp/target"); // Read symbolic link target String target = sftp.readlink("/tmp/link"); // Get canonical/absolute path String canonical = sftp.canonicalize("./relative/path"); // Open file for reading/writing RemoteFile file = sftp.open("/tmp/file.txt", EnumSet.of(OpenMode.READ)); try { byte[] buffer = new byte[1024]; int bytesRead = file.read(0, buffer, 0, buffer.length); } finally { file.close(); } } finally { sftp.close(); } } finally { ssh.disconnect(); } ``` -------------------------------- ### Load Private Keys for SSH Authentication (Java) Source: https://context7.com/hierynomus/sshj/llms.txt Demonstrates loading private keys from files or strings for public key authentication. Supports unencrypted and encrypted keys, and interactive passphrase input using PasswordFinder. Requires SSHJ library. ```java import net.schmizz.sshj.SSHClient; import net.schmizz.sshj.userauth.keyprovider.KeyProvider; import net.schmizz.sshj.userauth.password.PasswordFinder; import net.schmizz.sshj.userauth.password.Resource; SSHClient ssh = new SSHClient(); ssh.loadKnownHosts(); ssh.connect("hostname"); try { // Load unencrypted key from file KeyProvider keys = ssh.loadKeys("/path/to/id_rsa"); ssh.authPublickey("username", keys); // Load encrypted key with passphrase KeyProvider encryptedKeys = ssh.loadKeys("/path/to/id_rsa", "my-passphrase"); ssh.authPublickey("username", encryptedKeys); // Load key with PasswordFinder (for interactive passphrase input) KeyProvider interactiveKeys = ssh.loadKeys("/path/to/id_rsa", new PasswordFinder() { @Override public char[] reqPassword(Resource resource) { // Return passphrase (e.g., from user input) return "passphrase".toCharArray(); } @Override public boolean shouldRetry(Resource resource) { return false; // Don't retry on failure } }); ssh.authPublickey("username", interactiveKeys); // Load key from string content String privateKeyContent = "-----BEGIN RSA PRIVATE KEY-----\\n..."; String publicKeyContent = "ssh-rsa AAAA..."; KeyProvider stringKeys = ssh.loadKeys(privateKeyContent, publicKeyContent, null); ssh.authPublickey("username", stringKeys); } finally { ssh.disconnect(); } ``` -------------------------------- ### Jump Host / Bastion Server Connection with SSHJ Source: https://context7.com/hierynomus/sshj/llms.txt Establishes a connection to a target server by first connecting to an intermediate 'jump' host. This is useful for accessing servers not directly reachable from the client. It utilizes SSHJ's `DirectConnection` to create a tunnel. ```java import net.schmizz.sshj.SSHClient; import net.schmizz.sshj.common.IOUtils; import net.schmizz.sshj.connection.channel.direct.DirectConnection; import net.schmizz.sshj.connection.channel.direct.Session; import java.util.concurrent.TimeUnit; // Connect to jump host SSHClient jumpHost = new SSHClient(); jumpHost.loadKnownHosts(); jumpHost.connect("jump.example.com"); try { jumpHost.authPublickey(System.getProperty("user.name")); // Create tunnel through jump host to target DirectConnection tunnel = jumpHost.newDirectConnection("internal-server.local", 22); // Connect to target through the tunnel SSHClient target = new SSHClient(); try { target.loadKnownHosts(); target.connectVia(tunnel); target.authPublickey(System.getProperty("user.name")); // Execute command on target server Session session = target.startSession(); try { Session.Command cmd = session.exec("hostname"); System.out.println(IOUtils.readFully(cmd.getInputStream()).toString()); cmd.join(5, TimeUnit.SECONDS); } finally { session.close(); } } finally { target.disconnect(); } } finally { jumpHost.disconnect(); } ``` -------------------------------- ### Manage I/O Streams with sshj Channels Source: https://github.com/hierynomus/sshj/wiki/Home Demonstrates how to access standard input, output, and error streams from sshj channels. These methods allow for reading and writing data during command, shell, or subsystem execution. ```java // on any Channel, including Session.Command, Session.Shell and Session.Subsystem getOutputStream(); // -> java.io.OutputStream; corresponds to stdin getInputStream(); // -> java.io.InputStream; corresponds to stdout // only on Session.Command and Session.Shell getErrorStream(); // -> java.io.InputStream; corresponds to stderr // only on Session.Command getOutputAsString(); // -> java.lang.String; blocks until it reads all data from stdout ``` -------------------------------- ### SCP File Transfer in Java Source: https://context7.com/hierynomus/sshj/llms.txt Illustrates how to perform file uploads and downloads using the SCP protocol with optional compression for faster transfers. Requires SSHClient and SCPFileTransfer from the SSHJ library. JZlib is needed for compression. ```java import net.schmizz.sshj.SSHClient; import net.schmizz.sshj.xfer.FileSystemFile; import java.io.File; SSHClient ssh = new SSHClient(); ssh.loadKnownHosts(); ssh.connect("localhost"); try { ssh.authPublickey(System.getProperty("user.name")); // Enable compression (requires JZlib in classpath) ssh.useCompression(); // Upload file via SCP String localFile = System.getProperty("user.home") + File.separator + "test_file"; ssh.newSCPFileTransfer().upload(new FileSystemFile(localFile), "/tmp/"); // Download file via SCP ssh.newSCPFileTransfer().download("remote_file", new FileSystemFile("/tmp/")); // Bandwidth-limited transfer (in kilobits/second) ssh.newSCPFileTransfer().bandwidthLimit(1024).upload(new FileSystemFile(localFile), "/tmp/"); } finally { ssh.disconnect(); } ``` -------------------------------- ### Enable X11 Forwarding for Remote Graphical Applications (Java) Source: https://context7.com/hierynomus/sshj/llms.txt This snippet demonstrates how to configure SSHJ to forward X11 graphical applications from a remote server to a local display. It requires an SSH client, setting up X11 forwarding before connecting, and requesting X11 forwarding with an authentication cookie. The output streams of the remote command are copied to local stdout and stderr. ```java import net.schmizz.sshj.SSHClient; import net.schmizz.sshj.common.StreamCopier; import net.schmizz.sshj.common.LoggerFactory; import net.schmizz.sshj.connection.channel.direct.Session; import net.schmizz.sshj.connection.channel.direct.Session.Command; import net.schmizz.sshj.connection.channel.forwarded.SocketForwardingConnectListener; import java.net.InetSocketAddress; SSHClient ssh = new SSHClient(); ssh.loadKnownHosts(); // Register X11 forwarder BEFORE connecting // Forward to local X server (requires X started with TCP listening) ssh.registerX11Forwarder(new SocketForwardingConnectListener( new InetSocketAddress("localhost", 6000) )); ssh.connect("remote-server"); try { ssh.authPublickey(System.getProperty("user.name")); Session session = ssh.startSession(); // Request X11 forwarding with authentication cookie // Get cookie from: xauth list session.reqX11Forwarding( "MIT-MAGIC-COOKIE-1", // Protocol "b0956167c9ad8f34c8a2788878307dc9", // Cookie 0 // Screen number ); // Execute graphical application Command cmd = session.exec("/usr/bin/xcalc"); new StreamCopier(cmd.getInputStream(), System.out, LoggerFactory.DEFAULT).spawn("stdout"); new StreamCopier(cmd.getErrorStream(), System.err, LoggerFactory.DEFAULT).spawn("stderr"); // Wait for X11 channel to close ssh.getConnection().join(); } finally { ssh.disconnect(); } ``` -------------------------------- ### Add BouncyCastle Dependencies for Enhanced Cryptography Source: https://github.com/hierynomus/sshj/wiki/Maven Includes the BouncyCastle provider and PKIX libraries as optional dependencies to provide improved cryptographic support for sshj. ```xml org.bouncycastle bcprov-jdk15on 1.50 org.bouncycastle bcpkix-jdk15on 1.50 ``` -------------------------------- ### Customize SSH Client Configuration (Java) Source: https://context7.com/hierynomus/sshj/llms.txt This Java code snippet illustrates how to customize SSHJ client configurations, including setting keep-alive providers, defining cipher preferences (e.g., AES-GCM, AES-CTR), and enabling compression. It shows how to create a `DefaultConfig` object, modify its settings, and then instantiate an `SSHClient` with this custom configuration. ```java import net.schmizz.sshj.DefaultConfig; import net.schmizz.sshj.SSHClient; import net.schmizz.sshj.keepalive.KeepAliveProvider; import com.hierynomus.sshj.transport.cipher.BlockCiphers; import com.hierynomus.sshj.transport.cipher.GcmCiphers; import net.schmizz.sshj.transport.compression.DelayedZlibCompression; import net.schmizz.sshj.transport.compression.ZlibCompression; import net.schmizz.sshj.transport.compression.NoneCompression; import java.util.Arrays; // Create custom configuration DefaultConfig config = new DefaultConfig(); // Set keep-alive provider config.setKeepAliveProvider(KeepAliveProvider.HEARTBEAT); // Customize cipher preferences config.setCipherFactories(Arrays.asList( GcmCiphers.AES256GCM(), GcmCiphers.AES128GCM(), BlockCiphers.AES256CTR(), BlockCiphers.AES192CTR(), BlockCiphers.AES128CTR() )); // Create client with custom config SSHClient ssh = new SSHClient(config); // Enable compression after connection (triggers renegotiation) ssh.loadKnownHosts(); ssh.connect("hostname"); try { ssh.authPublickey("username"); // Enable zlib compression ssh.useCompression(); // ... perform file transfers with compression ... } finally { ssh.disconnect(); } ``` -------------------------------- ### Add jzlib Dependency for Compression Source: https://github.com/hierynomus/sshj/wiki/Maven Includes the jzlib library as an optional dependency to enable zlib compression features within sshj. ```xml com.jcraft jzlib 1.1.3 ``` -------------------------------- ### Configure Sonatype Snapshot Repository in Maven Source: https://github.com/hierynomus/sshj/wiki/Maven Adds the Sonatype remote repository to the Maven project configuration to allow the retrieval of snapshot versions of the sshj library. ```xml sonatype http://oss.sonatype.org/content/groups/public/ ``` -------------------------------- ### Configure In-Memory Known Hosts for SSH Verification (Java) Source: https://context7.com/hierynomus/sshj/llms.txt Sets up SSH host key verification using an in-memory string representation of known hosts, bypassing file-based storage. Requires SSHJ library and Java's NIO for byte stream handling. ```java import net.schmizz.sshj.SSHClient; import net.schmizz.sshj.transport.verification.OpenSSHKnownHosts; import java.io.ByteArrayInputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; // Known hosts entry in OpenSSH format String knownHostEntry = "localhost ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPmhSBtMctNa4hsZt8QGlsYSE5/gMkjeand69Vj4ir13"; ByteArrayInputStream entry = new ByteArrayInputStream( knownHostEntry.getBytes(Charset.defaultCharset()) ); SSHClient ssh = new SSHClient(); ssh.addHostKeyVerifier(new OpenSSHKnownHosts( new InputStreamReader(entry, Charset.defaultCharset()) )); ssh.connect("localhost"); try { ssh.authPublickey(System.getProperty("user.name")); // ... perform operations ... } finally { ssh.disconnect(); } ``` -------------------------------- ### Local Port Forwarding in Java Source: https://context7.com/hierynomus/sshj/llms.txt Sets up local port forwarding to tunnel connections from a local port to a remote destination through an SSH server. Requires SSHClient, LocalPortForwarder, and Parameters from the SSHJ library. Uses standard Java networking classes. ```java import net.schmizz.sshj.SSHClient; import net.schmizz.sshj.connection.channel.direct.LocalPortForwarder; import net.schmizz.sshj.connection.channel.direct.Parameters; import java.net.InetSocketAddress; import java.net.ServerSocket; SSHClient ssh = new SSHClient(); ssh.loadKnownHosts(); ssh.connect("localhost"); try { ssh.authPublickey(System.getProperty("user.name")); // Forward localhost:8080 -> google.com:80 through SSH server Parameters params = new Parameters( "0.0.0.0", // Local address to bind 8080, // Local port "google.com", // Remote host (from SSH server's perspective) 80 // Remote port ); ServerSocket serverSocket = new ServerSocket(); serverSocket.setReuseAddress(true); serverSocket.bind(new InetSocketAddress(params.getLocalHost(), params.getLocalPort())); try { // This blocks and handles incoming connections ssh.newLocalPortForwarder(params, serverSocket).listen(); } finally { serverSocket.close(); } } finally { ssh.disconnect(); } ``` -------------------------------- ### Add SSHJ Dependency for Maven and Gradle Source: https://context7.com/hierynomus/sshj/llms.txt This section provides the necessary dependency declarations for integrating the SSHJ library into Java projects using either Maven or Gradle build tools. It specifies the group ID, artifact ID, and version for easy inclusion in your project's build configuration. ```xml com.hierynomus sshj 0.38.0 ``` ```groovy // Gradle implementation 'com.hierynomus:sshj:0.38.0' ``` -------------------------------- ### SFTP File Download Operations (Java) Source: https://context7.com/hierynomus/sshj/llms.txt Enables downloading files from remote servers via SFTP using the SSHJ library. It allows downloading to a local file, using string paths for both remote and local files, and resuming interrupted downloads from a specified byte offset. Requires SSHJ library. ```java import net.schmizz.sshj.SSHClient; import net.schmizz.sshj.sftp.SFTPClient; import net.schmizz.sshj.xfer.FileSystemFile; SSHClient ssh = new SSHClient(); ssh.loadKnownHosts(); ssh.connect("localhost"); try { ssh.authPublickey(System.getProperty("user.name")); SFTPClient sftp = ssh.newSFTPClient(); try { // Download to a local file sftp.get("remote_file", new FileSystemFile("/tmp")); // Download with string paths sftp.get("/remote/path/file.txt", "/local/path/file.txt"); // Resume download from byte offset sftp.get("/remote/path/largefile.zip", "/local/path/largefile.zip", 512000); } finally { sftp.close(); } } finally { ssh.disconnect(); } ``` -------------------------------- ### Add SSHJ Dependency to Maven Source: https://github.com/hierynomus/sshj/blob/master/README.adoc This snippet provides the XML configuration required to include the sshj library in a Maven-based Java project. It specifies the group ID, artifact ID, and current version for the dependency. ```xml com.hierynomus sshj 0.38.0 ``` -------------------------------- ### SFTP File Upload Operations (Java) Source: https://context7.com/hierynomus/sshj/llms.txt Utilizes the SFTPClient from SSHJ to upload files and directories to remote servers. Supports uploading single files, files specified by string paths, and resuming interrupted uploads from a specific byte offset. Requires SSHJ library. ```java import net.schmizz.sshj.SSHClient; import net.schmizz.sshj.sftp.SFTPClient; import net.schmizz.sshj.xfer.FileSystemFile; import java.io.File; SSHClient ssh = new SSHClient(); ssh.loadKnownHosts(); ssh.connect("localhost"); try { ssh.authPublickey(System.getProperty("user.name")); SFTPClient sftp = ssh.newSFTPClient(); try { // Upload a single file String localFile = System.getProperty("user.home") + File.separator + "test_file"; sftp.put(new FileSystemFile(localFile), "/tmp"); // Upload with string paths sftp.put("/local/path/file.txt", "/remote/path/file.txt"); // Resume an interrupted upload (start from byte offset) sftp.put("/local/path/largefile.zip", "/remote/path/largefile.zip", 1024000); } finally { sftp.close(); } } finally { ssh.disconnect(); } ``` -------------------------------- ### Configure SSH Keep-Alive for Connection Stability (Java) Source: https://context7.com/hierynomus/sshj/llms.txt Enables keep-alive messages to prevent idle SSH connections from timing out. Configures the interval before establishing the connection. Requires SSHJ and its keep-alive provider. ```java import net.schmizz.keepalive.KeepAliveProvider; import net.schmizz.sshj.DefaultConfig; import net.schmizz.sshj.SSHClient; import net.schmizz.sshj.connection.channel.direct.Session; import net.schmizz.sshj.transport.verification.PromiscuousVerifier; // Configure keep-alive provider in DefaultConfig DefaultConfig config = new DefaultConfig(); config.setKeepAliveProvider(KeepAliveProvider.KEEP_ALIVE); SSHClient ssh = new SSHClient(config); try { ssh.addHostKeyVerifier(new PromiscuousVerifier()); // Set keep-alive interval BEFORE connecting ssh.getConnection().getKeepAlive().setKeepAliveInterval(5); // seconds ssh.connect("hostname"); ssh.authPassword("username", "password"); Session session = ssh.startSession(); try { session.allocateDefaultPTY(); // Long-running session - keep-alive prevents timeout // ... } finally { session.close(); } } finally { ssh.disconnect(); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.