php 在 Cisco 路由器上执行命令的脚本
php script to execute commands on Cisco router
我需要编写一个脚本来连接到 Cisco 路由器并执行命令。 linux 服务器和 Cisco 路由器使用 ssh 密钥,因此不需要 username/password。我知道如何建立连接,但我不知道如何发出命令和读取响应。
注意:它必须在 php 中才能与我们正在进行的其他一些事情集成。
这是我目前的情况:-
<?php
$connection = ssh2_connect("n.n.n.n", 22, array("hostkey"=>"ssh-rsa"));
if(!$connection)
{
die("Could not connect to the Router \n\r");
exit();
}
if (ssh2_auth_none ($connection, "username"))
{
echo("Public Key Authentication Successful\n\r");
}
else
{
die("Public Key Authentication Failed");
exit();
}
// New commands based on help received
try
{
$command = "dir";
$stream = ssh2_exec($connection, $command);
// added to test if the ssh2_exec command returns false - which it does, issue is with the command ???
if(!$stream)
{
echo("Command returned False\n\r");
exit();
}
$errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);
stream_set_blocking($errorStream, true);
stream_set_blocking($stream, true);
$errorStreamContent = stream_get_contents($errorStream);
$streamContent = stream_get_contents($stream);
echo("ErrorStream : " . $errorStreamContent . "\n" . "Stream : " .
$streamContent . "\n\r");
}
catch(exception $e)
{
echo("Error : " . $e);
exit();
}
?>
现在输出如下:-
Public Key Authentication Successful
Command returned False
谁能告诉我发出命令和读取任何结果的正确方法?谢谢
我设法通过使用 ssh2_auth_pubkey_file 将 ssh 密钥传递给路由器并进行身份验证来解决此问题。之后一切正常。
我需要编写一个脚本来连接到 Cisco 路由器并执行命令。 linux 服务器和 Cisco 路由器使用 ssh 密钥,因此不需要 username/password。我知道如何建立连接,但我不知道如何发出命令和读取响应。
注意:它必须在 php 中才能与我们正在进行的其他一些事情集成。
这是我目前的情况:-
<?php
$connection = ssh2_connect("n.n.n.n", 22, array("hostkey"=>"ssh-rsa"));
if(!$connection)
{
die("Could not connect to the Router \n\r");
exit();
}
if (ssh2_auth_none ($connection, "username"))
{
echo("Public Key Authentication Successful\n\r");
}
else
{
die("Public Key Authentication Failed");
exit();
}
// New commands based on help received
try
{
$command = "dir";
$stream = ssh2_exec($connection, $command);
// added to test if the ssh2_exec command returns false - which it does, issue is with the command ???
if(!$stream)
{
echo("Command returned False\n\r");
exit();
}
$errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);
stream_set_blocking($errorStream, true);
stream_set_blocking($stream, true);
$errorStreamContent = stream_get_contents($errorStream);
$streamContent = stream_get_contents($stream);
echo("ErrorStream : " . $errorStreamContent . "\n" . "Stream : " .
$streamContent . "\n\r");
}
catch(exception $e)
{
echo("Error : " . $e);
exit();
}
?>
现在输出如下:-
Public Key Authentication Successful
Command returned False
谁能告诉我发出命令和读取任何结果的正确方法?谢谢
我设法通过使用 ssh2_auth_pubkey_file 将 ssh 密钥传递给路由器并进行身份验证来解决此问题。之后一切正常。