PHP code example of detain / sshwitch

1. Go to this page and download the library: Download detain/sshwitch 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 / sshwitch example snippets



Detain\Sshwitch\Sshwitch;

// 1. Tell sshwitch how to reach your relay box
define('CLOGIN_SSH_HOST', '10.0.0.1');
define('CLOGIN_SSH_PORT', 22);
define('CLOGIN_SSH_USER', 'sshuser');
define('CLOGIN_SSH_KEY',  '/home/sshuser/.ssh/id_rsa');

// 2. Run commands against a target switch through that relay
$result = Sshwitch::run('switch01.example.net', [
    'show version',
    'show ip interface brief',
]);

if ($result === false) {
    fwrite(STDERR, "Failed to talk to the switch.\n");
    exit(1);
}

foreach ($result as $i => $output) {
    echo "=== Command #{$i} ===\n{$output}\n";
}

Sshwitch::setChaining(true)
    ::setTimeout(15)
    ::setAutoDisconnect(false)
    ::run('switch01.example.net', 'show version');

// Disable chaining when you actually want a value back:
$output = Sshwitch::setChaining(false)::getOutput();

$out = Sshwitch::run('sw01.example.net', 'show clock');
echo $out[0] ?? 'no output';

Sshwitch::run('sw01.example.net', 'show version;show clock;show ip route summary');

Sshwitch::setAutoDisconnect(false);
Sshwitch::run('sw01.example.net', 'show version');
Sshwitch::run('sw02.example.net', 'show version');
Sshwitch::disconnect();

$parsed = Sshwitch::run('sw01.example.net', 'show inventory');

echo "Raw transcript:\n",   Sshwitch::getOutput(),   "\n\n";
echo "Parsed entries:\n",   print_r($parsed, true);
echo "Device hostname:\n",  Sshwitch::getHostname(), "\n";

$result = Sshwitch::run('sw01.example.net', 'show version');
if ($result === false) {
    error_log('switch run failed; raw output: ' . Sshwitch::getOutput());
}

   ┌────────────┐   ssh2 (php-ssh2)   ┌─────────────┐    clogin    ┌────────────┐
   │ your PHP   │ ──────────────────► │  relay box  │ ───────────► │  switch /  │
   │ script     │ ◄────────────────── │ (CLOGIN_*)  │ ◄─────────── │   router   │
   └────────────┘                     └─────────────┘              └────────────┘