Execute sudo from a cron script

Recently I bumped into this problem, and I wanted to share it’s easy solution:

Say you want to execute:

0 6 * * * /home/oraias/cron/restart.sh

Contents restart.sh:

PID=$(ps aux | grep tomcat8 | grep -v grep | tr -s ” ” | cut -d” ” -f2)
kill -9 $PID
sleep 5
sudo systemctl start tomcat8

Each day at 6AM cron launches this script. It looks up the PID of a Java process with “tomcat8” in it’s argument list. Kills the process and starts it again. Since this script is being launched as a non-root user, sudo is required for systemctl operation (assuming you configured the sudoers file).

It might happen that the last line of the script silently fails. If this is also your case, check the following options in /etc/sudoers (make sure to open it with sudoedit):

# Disable “ssh hostname sudo <cmd>”, because it will show the password in clear.
# You have to run “ssh -t hostname sudo <cmd>”.
Defaults requiretty

# Refuse to run if unable to disable echo on the tty. This setting should also be
# changed in order to be able to use sudo without a tty. See requiretty above.
Defaults !visiblepw

Since cron doesn’t launch any TTY, the above options cause sudo to fail silently.

Comment out both to change this behavior.



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s