Skip to content

Instantly share code, notes, and snippets.

@gmolveau
Last active July 28, 2020 09:45
Show Gist options
  • Select an option

  • Save gmolveau/89af45845defaa3da46ba27645bc15b7 to your computer and use it in GitHub Desktop.

Select an option

Save gmolveau/89af45845defaa3da46ba27645bc15b7 to your computer and use it in GitHub Desktop.
Run a script periodically with cron and sudo

inspiration (and concrete example) : https://kevq.uk/how-to-backup-nextcloud/

  • creating the dedicated user
# Create new user
sudo adduser <GOOD_LOGICAL_USERNAME>

if this user needs to store some data :

# Switch to new user account
su --login <GOOD_LOGICAL_USERNAME>
# or sudo su --login <GOOD_LOGICAL_USERNAME>

# Create some folders
mkdir -p <Data>/<something>

# Switch back
logout
  • put your script into usr/sbin

make sure your bash script is secure (cf shellcheck / shfmt)

usr/sbin requires sudo privileges, a good choice to store the script

sudo cp <YOUR_SCRIPT>.sh /usr/sbin/<YOUR_SCRIPT>.sh

  • logging you said ?

if you want to see what your script did, you can redirect stdout and stderr to a file (so when you echo, it will be printed in a file)

cf : https://www.gnu.org/software/bash/manual/html_node/Redirections.html ; https://www.howtogeek.com/435903/what-are-stdin-stdout-and-stderr-on-linux/

[...]

# &> redirects both stdout and stderr
exec &> /home/<GOOD_LOGICAL_USERNAME>/Data/Logs/"$(date '+%Y-%m-%d').txt"
echo "This line will be in the file and not on the screen..."

[...]

or you can specify this option when calling the script in cron : /usr/sbin/<YOUR_SCRIPT>.sh >> /home/<GOOD_LOGICAL_USERNAME>/Data/Logs/"$(date '+%Y-%m-%d').txt" 2>&1

cf : https://unix.stackexchange.com/a/52332

  • make it executable

sudo chmod +x /usr/sbin/<YOUR_SCRIPT>.sh

  • make sure visudo is installed

  • add the new user to sudo group without password

# Open visudo
sudo visudo

# Allow <GOOD_LOGICAL_USERNAME> to run script as sudo
<GOOD_LOGICAL_USERNAME> ALL=(ALL) NOPASSWD: /usr/sbin/<YOUR_SCRIPT>.sh
  • disable login for the new user
sudo usermod -s /sbin/nologin <GOOD_LOGICAL_USERNAME>

if you want to login later, use this command to allow login with bash : sudo usermod -s /bin/bash <GOOD_LOGICAL_USERNAME>

  • add the script to cron for the new user :
sudo crontab -u <GOOD_LOGICAL_USERNAME> -e

and add those cron lines : (cron uses a special syntax)

cf : https://cron.help ; https://crontab.guru/ ; https://crontab.guru/examples.html ; https://crontab-generator.org/

# script cron (runs at 2am daily)
0 2 * * * sudo /usr/sbin/<YOUR_SCRIPT>.sh

!!! Congratulations, you should be ready to go !!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment