PHP - Issue a command using ssh2_exec

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.

$server = "";
$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 />";

$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 />";

$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 />";

Did you find this article helpful?

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

Add a Comment

We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.

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