omega1
omega1

Reputation: 1052

Editing a users crontab via bash script called via PHP

I am attempting to create a user and add an entry to a users crontab (any user on the system) via a PHP script (running on the same server) which calls a bash script.

I have solved the problem about creating a user, this works OK, but the last line in the bash script to add an entry to that new users crontab does not work when called via the PH script. I have confirmed that it does work when run locally.

I have the following PHP script:

<?php
//system("whoami");
chdir('/var/www/html/sandpit/users/');
$user = "test2";
$user=escapeshellarg($user);
$output = shell_exec("./create_user.sh $user");
echo "<pre>$output</pre>";
//echo "<br>ends";
?>

And the content of create_user.sh is :

#!/bin/bash
export user=$1 
sudo /usr/sbin/useradd $user -M
sudo echo "0 1 * * * /root/test.sh" | tee -a /var/spool/cron/crontabs/test2

In the last line I have hardcoded the variable into the actual name 'test2' to deal with one issue at a time, though I know $user to contain 'test2' because it correctly creates the user.

I have added these line to /etc/sudoers:

www-data ALL=(ALL:ALL) ALL
www-data ALL=(ALL) NOPASSWD: ALL

So my question is, why does the last line to edit the users crontab work when run locally (as root) but not run when called via the script? I assume that it is a permissions issue as I know the command line to work correctly as it runs manually.

Any help would be appreciated. Thanks.

Upvotes: 0

Views: 83

Answers (1)

Gerd K
Gerd K

Reputation: 1147

You need sudo for tee not for echo. tee is not executed with root privileges.

Upvotes: 1

Related Questions