PHP - Authenticate to an SSH server using ssh2_auth_pubkey_file

by
Jeremy Canfield |
Updated: January 31 2022
| 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