Change Date and Time without SUDO password?

I am installing a RPi with DietPi as an offline webserver on a boat. I want to update the RPi time and date with data from a GPS module using a PHP script.

How can I change the time and date (either “date” or “timedatectl set-time”) without having to enter the sudo password?

I’ve added the www-data user to the sudoers file, as well as the script, which changes the time and date as follows:


# Allow members of group sudo to execute any command
%sudo   ALL=(ALL:ALL) ALL
www-data        ALL=(ALL:ALL) ALL

# See sudoers(5) for more information on "@include" directives:

@includedir /etc/sudoers.d

www-data        ALL=(ALL:ALL) ALL /var/www/html/update_time.php
www-data        ALL=(ALL:ALL) ALL /bin/date

The update_time.php script looks as follows:

<?php
  $date = "12:01:12";
  $cmd = 'sudo date -s' . $date;
  shell_exec($cmd);
?>

Thanks for any ideas.

First of all the syntax for sudoers is wrong and also the path to date. The first line is also not necessary, bc www-data does not need super user privileges to execute the php script. Also check the permissions and ownership of the php file, the webserver must be able to execute it. We can check it with ls -la /var/www/html/update_time.php.

Sudoers:

www-data ALL=(ALL) NOPASSWD: /usr/bin/date
2 Likes