Run a command with sudo in bash shell

10.5k views Asked by At

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.

5

There are 5 answers

0
jcalloway On BEST ANSWER

echo 'password' | sudo -S command

0
Beeble42 On

Why not run the script itself as root in cron since that is basically what sudo would do? Are you talking about a user crontab?

0
pBuch On

Enter the cronjob in

sudo crontab -e 

then the whole script will be executed as root per default without the need of a password.

1
Leonel De Leon On

I think you are trying do this:

       user# crontab -e
        * * * * * sudo ./code_here

But every time the script is call you ned to provide the credentials

So you can try this:

       user# sudo su
        root# crontab -e
       * * * * *    ./code goes here

In this way: it will run with administrator privileges.

0
Rammix On

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.