How To Execute SSH Commands Via PHP

How To Execute SSH Commands Via PHP

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

The Perils of Shell Execution and the SSH2 Extension

Using shell_exec("ssh user@host.com mkdir /testing") feels intuitive, but it is a significant security risk. This approach treats your application as a conduit for arbitrary shell commands, bypassing PHP's standard input validation and exposing your server to command injection vulnerabilities. If an attacker can manipulate the arguments passed into that string before they reach the shell, they gain direct access to the remote host.

The most secure alternative is leveraging the ssh2 extension, which provides a native PHP interface to the SSH-2 protocol without relying on spawning external shell processes. This method allows you to establish a secure tunnel, authenticate, and execute commands programmatically while maintaining strict control over the data flow. The trade-off is that it requires a compiled extension rather than a simple function call, but the security benefits are substantial.

To get started, ensure you have the ssh2 extension enabled in your environment. You can verify its availability with:

if (extension_loaded('ssh2')) {
    echo "SSH2 is available.";
} else {
    echo "SSH2 is not loaded.";
}

Once confirmed, you can instantiate an ssh2_connect object to establish a connection. The first parameter is the host address and port, while the second allows for key exchange algorithm negotiation if needed.

$host = 'example.com';
$port = 22;

$context = stream_context_create([
    'ssl' => [
        'verify_peer' => true,
        'verify_peer_name' => true,
    ]
]);

$conn = ssh2_connect($host, $port);

if (!$conn) {
    throw new Exception("Could not connect to SSH server.");
}

After connecting, you must authenticate. The ssh2_auth_pubkey_file function is generally preferred over password authentication because it avoids transmitting credentials in cleartext and does not require storing passwords directly in the codebase or environment variables unless absolutely necessary. You will need a private key file path, its passphrase (if set), and optionally the public key for verification.

$privateKeyPath = '/path/to/private_key';
$passphrase = 'your-passphrase-here'; // Only needed if the key is encrypted

$authContext = ssh2_auth_pubkey_file(
    $conn,
    null,          // username (null implies current or derived)
    $privateKeyPath,
    $passphrase,
    '/path/to/authorized_keys' // optional, usually handled by server side
);

Note that in many deployment scenarios, the public key is pre-installed on the remote server under .ssh/authorized_keys, so passing it manually here is often redundant. The critical part is ensuring the private key remains secure and never exposed via logs or error pages.

Once authenticated, you can execute commands using ssh2_exec. This returns a resource that behaves like a stream, allowing you to write commands and read output safely.

$command = 'mkdir /testing';
$result = ssh2_exec($conn, $command);

if ($result) {
    $output = stream_get_contents($result);
    echo "Output: {$output}";
    
    // Close the channel
    ssh2_channel_close($result);
    ssh2_channel_send_eof($result);
} else {
    echo "Command execution failed.";
}

This approach keeps your logic isolated from shell interpretation quirks and avoids the pitfalls of shell_exec. It also makes debugging easier since you’re not relying on environment-specific shell behavior.

One common pitfall is forgetting to close the connection or channel resources after use, which can lead to resource leaks in long-running applications. Always wrap SSH operations in try-catch blocks and ensure proper cleanup.

For production-grade PHP applications, especially those built with frameworks like Laravel, integrating this pattern cleanly requires careful abstraction. While specific libraries may offer helper functions, understanding the underlying ssh2 API ensures you can handle edge cases securely. For more advanced integration patterns or managed SSH solutions, consider exploring resources from https://laravelcompany.com.

Our network