I would like to run a cron job as a specific user on my machine. How may I specify the user for a cron job to run as?.
The cron jobs will be running on a server (running on Ubuntu 10.0.4). The 'users' are users that have been created specifically for carrying out specific server side tasks. These 'users' have the following in common:
- Cannot log onto the system
- Have restricted access to specific folders/files
4 Answers
Assuming you can't just log in and add it to that user's crontab, put a file in /etc/cron.d. It should be formatted as a normal cronjob, but with an extra field. Before the command to run and after the timing, put the user. You should be able to find examples already on your system.
Example:
#<timing> <user> <command>
11 * * * * root /usr/lib/command 3 As root, to edit the cron of user1:
crontab -u user1 -eYou can also start your command with:
su user1 -c foo barBut often, the scripts themselves reduce their own access when started as root.
I have been looking for this for a couple weeks and this finally worked...
Create your script as user1
ssh user1@ipaddress
nano hourly-event.shenter some command
#!/bin/bash
echo "YAY it works" > /home/user1/yay.txtmake it executable
chmod 755 hourly-event.shedit the crontab for user1
sudo crontab -u user1 -eput a line at the bottom pointing to your script(s)
# m h dom mon dow command
* * * * * bash ./hourly-event.shexit - saving changes (it will show a /tmp directory when saving... it's ok)
wait for the turn of the minute
open your newly create yay.txt
nano /home/user1/yay.txtyou should now have a nano window open with "YAY it works" as the first and only line if the bottom of your nano window say New File... well.. i dunno
you can also check your newly crontab entry for user1 at: /var/spool/cron/crontabs/user1
PEACE
Sometimes you may want the user load his environment, especially when using rbenv, nvm, just like this:
0 0 * * * source ~/.bash_profile && cd /opt/app/current && bundle exec ruby ...(here the command source ~/.bash_profile will load your Ruby or Node environment.)