Whether to use sudo or just su
Q I have been trying to create a script to automate various processes. However, I can't figure out how to run certain parts of the script as root, and other parts as my normal user. I don't want to run the entire script as root, just the odd section. I tried just using the su command, and then realised that I was now a totally different user and no longer executing my script. I realise su isn't the best idea, but for testing purposes it's fine. Is there a way to do this? Am I nuts for even thinking about using su in a script? My second idea was to start another shell as root; however, I'm not entirely sure how to do that from a script.
A The su command starts a new shell process as a different user, so the script running it stops until that shell is closed. Using su in a script is a bad idea, and is often blocked because of the security risks. The safer option is to use sudo. This allows individual commands to be run by specified users, without them needing to know the root password. By default, sudo requires the user to enter their own password, but it is possible to allow some commands to be run without giving a password, which may suit your script. Specify the full path to the commands that you want the user to be able to run in the /etc/sudoers file, and specify 'NOPASSWD' if you do not want the script to stop to prompt for your password. Here is a typical entry that allows one user to mount and unmount filesystems without giving a password:
fred ALL = NOPASSWD: /bin/mount,/bin/umount
Note the comment at the top of the /etc/sudoers file - it should be edited with the visudo command, not loaded directly into an editor. Run visudo as root and it will load the file into whatever program you have defined in $EDITOR. You can change this at the time you run visudo with, for example
The reason for doing it this way is that visudo copies /etc/sudoers to a temporary file, loads that into your editor, then checks that your syntax is correct before copying the altered file back. It stops typo-inserting pixies breaking your system, which is considered by most experts to be A Good Thing.
- Whether to use sudo or just su
- User account in Ubuntu being refused sudo access
- Switching from sudo to su
- Sudo on CentOS
- Write backup script that only selects one file