PHP ssh2 multiple commands with output

55 Views Asked by At

I need help with ssh2 connection to the network device. for example I need 3 commands to enter to the router:

  1. enter to the configuration mode (command: configure)
  2. add some configuration string
  3. check syntax

here is my example:

<?php
function ssh_configure($host, $command) {
    $con = ssh2_connect($host, 22);
    ssh2_auth_password($con, 'username', 'password');
    $shell = ssh2_shell($con, 'xterm');
    stream_set_blocking($shell, true);
    if (is_array($command)) {
        foreach ($command as $commands) {
            fwrite( $shell, "$commands\n");
        }  
        sleep(2);
        fwrite($shell, "show | compare\n");
    }
}

$commands = array(
    "configure", 
    "set interfaces ps37 unit 2311 vlan-tags outer 3215 inner 2311",
);

ssh_configure("172.16.190.2", $commands);

In this case I need to display only

fwrite($shell, "show | compare\n");

command.

I tried it with ssh2_exec command but it logout after each command and then login back to execute another one

1

There are 1 best solutions below

0
On

I added in function:

while (!feof($shell)) {
    echo fgets($shell).PHP_EOL;
    if (empty(fgets($shell))) {
        exit;
    }
} 

now I see all outputs but feof($shell) allways false and program never ends, how can I tell to the program that there is no more messages from router?