【问题标题】:php script to execute commands on Cisco router在 Cisco 路由器上执行命令的 php 脚本
【发布时间】:2019-03-04 09:35:25
【问题描述】:

我需要编写一个脚本来连接到 Cisco 路由器并执行命令。 linux 服务器和 Cisco 路由器使用 ssh 密钥,因此不需要用户名/密码。我已经弄清楚如何建立连接,但我不知道如何发出命令和读取响应。

注意:它必须在 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

谁能给我正确的方法来发出命令并读取任何结果?谢谢。

【问题讨论】:

  • 嗨@paskl,刚刚向Linux操作系统发出命令,而不是路由器。
  • 哎呀,你是对的。 ssh2_exec 怎么样? ;)
  • @paskl - 我发出了以下命令$result = ssh2_exec($connection, $command); 这次我没有收到错误,但 $result 为空。 $command 是dir,所以我希望看到一个文件列表(如果我手动在路由器上发出 dir,我会看到)。
  • 查看文档以了解如何读取流。 php.net 上的函数文档页面上的 cmets 真的很有帮助。 :) (这里没有必要重复)

标签: php cisco


【解决方案1】:

我设法通过使用 ssh2_auth_pubkey_file 将 ssh 密钥传递给路由器并进行身份验证来解决此问题。之后就可以正常使用了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 2013-01-14
    相关资源
    最近更新 更多