How can i run a command in shell script with sudo? This script will be run by a cron job, so there should be no human intervention to enter a password manually.
Run a command with sudo in bash shell
10.5k views Asked by The Georgia AtThere are 5 answers
Can't comment so I'll try to write it as an answer.
Saving the root password as plaintext is a security risk. Saving a script in the root's crontab is also risky if the script is in a common user's folder - a user can (at least in some distros) delete the file even if can't write to it, then this file may be replaced by a malicious one with the same name (thus "injected" in root's cronjob).
Suggestion:
sudo visudo
and add there something like
username ALL= NOPASSWD: /home/username/scriptname.sh
Assign to the group of the user meant to start the script (e.g. 'users'), restrict permissions:
chown -v root:users /home/username/scriptname.sh
chmod -v 0650 /home/username/scriptname.sh
Then make the scriptname.sh immutable to prevent deletion (even by root, until the immutable flag is removed)
chattr +i /home/username/scriptname.sh
Additional benefit of placing commands in a script like this then putting it into sudoers config is it allows the user to run these commands only inside the script.
Now this script can be added either to root's or the user's crontab, something like this in case of the latter:
crontab -e
* 3 * * * sudo /home/username/scriptname.sh &> /home/username/scriptname.log
UPD minor edit.
echo 'password' | sudo -S command