我正在编写一个php脚本,通过ssh连接到vyos路由器,并使用命令备份配置
show configuration commands
。
当我从命令提示符连接时,它按预期工作
ssh vyos@1.1.1.99
Password: ****
$ show configuration
interfaces {
...
但这是我的脚本,我正在尝试使用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;
代码返回错误
Invalid command: [show]
我最好的猜测是这与PATH或其他环境变量有关。有任何想法吗?我正在使用vyatta / vyos vm图像来测试它。
答案 0 :(得分:2)
我认为你可能会更幸运phpseclib。例如:
$ssh = new Net_SSH2('192.168.171.50');
$ssh->login('vyos', 'vyos');
$ssh->read('$');
$ssh->write("show configuration running\n");
echo $ssh->read('$');
这也可能有用:
$ssh = new Net_SSH2('192.168.171.50');
$ssh->login('vyos', 'vyos');
echo $ssh->exec('show configuration running');
如果这不起作用,可能会:
$ssh = new Net_SSH2('192.168.171.50');
$ssh->login('vyos', 'vyos');
$ssh->enablePTY();
echo $ssh->exec('show configuration running');
JC的编辑如下:最终工作代码 - 必须将终端长度设置为0或代码在寻呼机上挂起。
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('$');