我正在编写一个PHP脚本以通过ssh连接到vyos路由器并使用以下命令备份配置show configuration commands
。
当我从命令提示符连接时,按预期工作
ssh [email protected]
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镜像进行测试。
最佳答案
我认为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('$');