Shell – sudo script – best practice

shell-scriptsudo

I have a script in which some of the commands need to be run as sudo.
I have seen it asserted that running sudo inside scripts is a bad idea, and that is is better to run the whole script as sudo (and then possibly modify sudoers for convenience, as described here).

I have thought about it, and can't actually see any reason not to run sudo commands inside scripts. Assuming the script and its directory are both owned by root, and therefore unadulterated, I can't see any difference, from a security point of view. (And even if it were, running the whole script as sudo would be no less dangerous). Am I missing something here?

Best Answer

Running sudo is a bad idea because you don't know what will happen and if it's really necessary:

  • Will a password prompt be shown? If so, who is going to type a password? Remember: your script may be run in a shell by a human, but could also be run in background, at startup, by cron or in other situations where a terminal is not available.

  • Will the user type her password if she sees the prompt? Personally, I would immediately stop scripts asking me for a password. Also, I may not even notice the prompt if your script produces a lot of output.

  • Is sudo available and configured? Can the current user run sudo? The answer to one of these question may be 'no', in which case you should let the user choose how to give your script the necessary privileges.

  • Are you sure you need to be superuser? Maybe I configured my system so that your script does not need root privileges at all, in which case sudo is totally unnecessary and can be very disturbing.

Please let me decide what privileges you need and how to give them to you.

Running sudo may be a good idea if you're root and you want to drop your privileges. For example, you may open a file that is owned by root and then immediately switch to nobody:nogroup for security reasons. Still, the problem that sudo may not be available or may not be configured remains.

Related Question