Ubuntu – How to avoid password request for sudo for crontab scripts

bashcommand linecronpasswordsudo

I need that a new user could execute sudo without any request of password, because this user has in crontab a .sh that uses sudo for some commands.

I created a new user on my ubuntu server 16.04 x64

adduser my-user sudo
gpasswd -a my-user sudo

Then using visuo i added this line, based on this question

my-user ALL=(ALL) NOPASSWD : ALL

Then rebooted

After reboot I logged in using my-user and tried to do sudo clear, but it ask me the sudo password.

NOTE: I've added the crontab using crontab -e my-user so I suppose my script is executed as my-user. In fact, the crontabbed script crashes telling me in the log about a sudo request of password. I really need to execute the script in this way to be able to create file with my-suer as owner.

Please tell me if some steps/lines were not needed and how to make able my-user to execute sudo without password request.

Thanks

PS: I seen this question, but I'm not able to make it working so I need a more precise explanation, because my situation is different: i'm running a crontab script and I need it do not ask for sudo password

Best Answer

Sometimes running a process from root's crontab may cause issues with initial file ownership and rwx mode; those may not be correctly preserved.

In any case:

1) to create a new user, keep it simple:

 $ sudo deluser my-user  # if "my-user" is a regular user
 $ adduser my-user
 $ sudo gpasswd -a my-user sudo

2) to include a new entry with a NOPASSWD tag in sudoers or in a file (e.g. /etc/sudoers.d/60_my-user_rules), make the colon stick to the tag, i.e. NOPASSWD:
I've not seen it before with interspersed space and yr rule becomes:

 my-user my-host = NOPASSWD: /full/path/to/cmd [parameter1 [| parameter2 [| ...]]]

Adding (ALL) before the NOPASSWD: is optional as the rule defaults to (ALL:ALL) anyway. You may however want to not only run your cmd/script with root privilege but also run it as either a given user (spec-user) or as a member of a given group (spec-group) or both. In that case, the rule becomes:

 my-user my-host = ([spec-user][:spec-group]) NOPASSWD: /full/path/to/cmd [parameter1 [| parameter2 [| ...]]]

This will actually restrict yr passwordless sudo disposition to one user, one host and one command. You can harden this rule by specifying the optional parameter(s) to that command. In that case the rule will apply only for that/those exact parameter(s).
For scripts, you could further harden this rule by ensuring that the rule applies only if the script was not modified in any way. This is a way to avoid script-hijacking. This is done through cmd-aliasing and specifying SHA-sums in /etc/sudoers.d/60_my-user_rules.

HTH. Please report if you experience issues with that answer.