2

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

hakre
  • 193,403
  • 52
  • 435
  • 836
  • 1
    Use `expect`: https://www.php.net/manual/en/book.expect.php to automate interactive applications. – Barmar Jul 28 '23 at 20:14
  • You have 3 problems: 1. To see the output of the command you need to read from the shell stream. 2. That output will include the MOTD, interactive shell prompts, and the command itself. 3. The connection closes because it goes out of scope at the end of the function call. `expect` should help with 1 and 2, either using an object or passing `$con` as a variable will help with 3. Although it might just be that you're talking to a router/switch with a wonky SSH implementation and not a "real" SSHd. – Sammitch Jul 28 '23 at 22:28

1 Answers1

0

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?