PHP code example of detain / sshpool

1. Go to this page and download the library: Download detain/sshpool library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

detain / sshpool example snippets




use Detain\SshPool\SshPool;

$pool = new SshPool(
    'example.com',          // host
    22,                     // port
    'deploy',               // ssh user
    '',                     // password (unused — pubkey auth)
    '/home/me/.ssh/id_rsa.pub',
    '/home/me/.ssh/id_rsa'
);

$pool->setMaxThreads(10);
$pool->setMaxRetries(2);

foreach (['uptime', 'df -h', 'free -m'] as $cmd) {
    $pool->addCommand(
        $cmd,
        null,                               // auto id
        ['command' => $cmd],                // user data passed to callback
        function ($cmd, $id, $data, $exit, $stdout, $stderr) {
            echo "[{$id}] {$cmd} (exit {$exit}):\n{$stdout}\n";
            if ($stderr !== '') {
                fwrite(STDERR, "[{$id}] stderr: {$stderr}\n");
            }
        },
        30                                  // 30s timeout
    );
}

$pool->run();

$result = $pool->runCommand('hostname');
// $result === ['cmd' => 'hostname', 'exitStatus' => 0, 'out' => '...', 'err' => '']

$pool->addCommand('first', null, null, function ($cmd, $id, $data, $exit) use ($pool) {
    if ($exit === 0) {
        // Chain a follow-up command.
        $pool->addCommand('second');
    }
});
$pool->run();

while (!$done) {
    $done = $pool->run(true);
    // ... do other work ...
}

$pool = new SshPool(
    $host, 22, $user, '', $pub, $priv,
    ['hostkey' => 'ssh-ed25519'] // deliberate single-algorithm pin
);

new SshPool(
    string $host,
    int $port,
    string $user,
    string $pass,
    string $pubKey,
    string $privKey,
    array $methods = []
);

string addCommand(
    string $cmd,
    ?string $id = null,
    mixed $data = null,
    ?callable $callback = null,
    int $timeout = 0
);

bool run(bool $once = false);
array|false runCommand(string $cmd);

void connect();
void disconnect();
resource|null getConnection();

function (
    string $cmd,
    string $id,
    mixed  $data,        // user data passed to addCommand()
    int    $exitStatus,  // -1 if unknown / timed out
    string $stdout,
    string $stderr
): void;

$pool->metadata['my-id'] === [
    'exit_status' => -1,
    'duration'    => 30,
    'timed_out'   => true,
];
bash
# Debian / Ubuntu
sudo apt-get install php-ssh2

# RHEL / Alma / Rocky
sudo dnf install php-pecl-ssh2