Category Archives: PHP

PHP function to remotely run command as root (su)

I rewrote this from somewhere and ended up not needing it, but in case I need it in the future, here it is.

The function ssh to the remote server, issues a su and then runs the command, returning true or false depending on the return code.

function RunRemoteAsRoot($ip, $username, $password, $rootPassword, $commandString)
{
	$connection = ssh2_connect($ip, 22);
	if (!$connection)
		return false;

	if (!ssh2_auth_password($connection, $username, $password))
		return false;

	$stream = ssh2_shell($connection, "vanilla", null, 200);
	if ($stream === false)
		return false;

	stream_set_blocking($stream, true);

	if (fputs($stream, "su -\n") === false)
	{
		fclose($stream);
		return false;
	}

	$line = "";
	$output = "";
	$returnCode = 1;
	while (($char = fgetc($stream)) !== false)
	{
		$line .= $char;
		if ($char != "\n")
		{
			if (preg_match("/Password:/", $line))
			{
				// Password prompt.
				if (fputs($stream, "{$rootPassword}\n{$commandString}\necho [end] $?\n") === false)
				{
					return false;
				}
				$line = "";
			}
			else if (preg_match("/incorrect/", $line))
			{
				//Incorrect root password
				return false;
			}
		}
		else
		{
			$output .= $line;
			if (preg_match("/\[end\]\s*([0-9]+)/", $line, $matches))
			{
				// End of command detected.
				$returnCode = $matches[1];
				break;
			}
			$line = "";
		}
	}
	fclose($stream);

	return ($returnCode == 0);
}