简体   繁体   中英

ssh2_exec environment trying to ssh to vyos router and get configuration

I am writing a php script to connect to a vyos router via ssh and backup the configuration using the command

show configuration commands .

When I connect from the command prompt this works as expected

ssh vyos@1.1.1.99
Password: ****
$ show configuration

interfaces {
...

But here is a my script where I'm trying to do the same thing using php.

<?php
//Connect to VyOS virtual router and backup config

$host = '192.168.171.50';
$user = 'vyos';
$pass = 'vyos';

$connection = ssh2_connect($host, 22 );
if (!$connection) die('Connection failed');

if (ssh2_auth_password($connection, $user, $pass)) {
  echo "Authentication Successful!\n";
} else {
  die('Authentication Failed...');
}

$stream = ssh2_exec($connection, 'show configuration' );
$errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);

// Enable blocking for both streams
stream_set_blocking($errorStream, true);
stream_set_blocking($stream, true);

echo "Output: " . stream_get_contents($stream);
echo "Error: " . stream_get_contents($errorStream);

// Close the streams        
fclose($errorStream);
fclose($stream);

exit;

The code returns the error

Invalid command: [show]

My best guess is this has something to do with the PATH or other environment variable. Any ideas? I'm using vyatta/vyos vm image to test this.

I think you might have better luck with phpseclib . For example:

$ssh = new Net_SSH2('192.168.171.50');
$ssh->login('vyos', 'vyos');

$ssh->read('$');
$ssh->write("show configuration running\n");
echo $ssh->read('$');

this might work too:

$ssh = new Net_SSH2('192.168.171.50');
$ssh->login('vyos', 'vyos');

echo $ssh->exec('show configuration running');

and if that does not work this might:

$ssh = new Net_SSH2('192.168.171.50');
$ssh->login('vyos', 'vyos');

$ssh->enablePTY();
echo $ssh->exec('show configuration running');

JC's Edit Below: Final Working Code - must set terminal length to 0 or code hangs on pager.

  include('Net/SSH2.php');
  $ssh = new \Net_SSH2('192.168.171.50');
  $ssh->login('vyos', 'vyos');

  $ssh->read('$');
  $ssh->write("set terminal length 0\n");
  $ssh->read('$');
  $ssh->write("show configuration\n");
  echo $ssh->read('$');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM