PHP - Issue a command using ssh2_exec

by
Jeremy Canfield |
Updated: October 15 2022
| PHP articles
ssh2_exec can be used to issue a command on a remote system using SSH2. Before using ssh2_exec, you will need to establish a connection to the SSH server using the ssh2_connection function and then the ssh2_auth_password or ssh2_auth_pubkey_file function to authenticate to the SSH server.
In this example, command "sudo chown john.doe /tmp/foo.txt" will be issued.
<?php
$server = "server1.example.com";
$connection = ssh2_connect($server, 22);
if ($connection) {
echo "Successfully connect to SSH server $server <br />";
}
else {
echo "Failed to connect to SSH server $server <br />";
exit();
}
$username = "john.doe";
$password = "itsasecret";
$authenticate = ssh2_auth_password($connection, $username, $password);
if ($authenticate) {
echo "Successfully authenticated to SSH server $server as $username <br />";
}
else {
echo "Failed to authenticate to SSH server $server as $username <br />";
exit();
}
$stream = ssh2_exec($connection, "sudo chown john.doe /tmp/foo.txt");
$stdout = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
$stderr = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);
stream_set_blocking($stdout, true);
stream_set_blocking($stderr, true);
$result_stdout = stream_get_contents($stdout);
$result_stderr = stream_get_contents($stderr);
echo "STDOUT Result = $result_stdout <br />";
echo "STDERR Result = $result_stderr <br />";
if ($result_stderr != "") {
echo "Got the following stderr when attempting 'sudo chown john.doe /tmp/foo.txt' on $server:<br />";
echo " $result_stderr<br />";
exit();
}
Did you find this article helpful?
If so, consider buying me a coffee over at