Bootstrap FreeKB - PHP - Authenticate to an SSH server using ssh2_auth_pubkey_file
PHP - Authenticate to an SSH server using ssh2_auth_pubkey_file

Updated:   |  PHP articles

The ssh2_auth_pubkey_file function can be used to authenticate to an SSH server from PHP using a public key so that a username and password are not needed via the ssh2_auth_password function.

Before using the ssh2_auth_password function, you will need to establish a connection to the SSH server using the ssh2_connection function.

In this example, username "john.doe" authenticates to the SSH server using his public key in /home/john.doe/.ssh/id_rsa.pub and /home/john.doe/.ssh/id_rsa (private key).

<?php
  $server = "server1.example.com";
  $connection = ssh2_connect($server, 22);

  if (!$connection) {
    echo "Failed to connect to SSH server $server <br />";
    exit();
  }
  else {
    echo "Successfully connect to SSH server $server <br />";
  }

  $username    = "john.doe";
  $public_key  = "/home/john.doe/.ssh/id_rsa.pub";
  $private_key = "/home/john.doe/.ssh/id_rsa";

  $authenticate = ssh2_auth_pubkey_file($connection, $username, $public_key, $private_key);

  if (!$authenticate) {
    echo "Failed to authenticate to SSH server $server as $username <br />";
    exit();
  }
  else {
    echo "Successfully authenticated to SSH server $server as $username <br /";
  }
?>

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 8d0101 in the box below so that we can be sure you are a human.