简体   繁体   中英

php script to execute commands on Cisco router

I need to write a script to connect to a Cisco router and execute commands. The linux server and the Cisco router use ssh keys so no username/password are required. I have worked out how to make the connection, but I don't know how to issue the commands and read the responses.

Note: It has to be in php to integrate with some other stuff we have going on.

Here is what I have so far :-

<?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();
}

?>

Output is now as follows :-

Public Key Authentication Successful
Command returned False

Can anyone give me the correct way to issue commands and read any result ? Thanks.

I managed to fix this by using ssh2_auth_pubkey_file to pass the ssh keys to the router and authenticate. After that it works fine.

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