Su and sudo in shell script

There is a shell script (/ bin / sh, not bash) that requires root privileges to execute.

If it is started as a normal user, it must ask the user for a password to gain root access and restart.

Now it uses the following code:

if [ $(id -u) -ne 0 ]; then su root -- $0 $@ ; ... fi

This works well, but there are some OSs like Ubuntu that don't have a root password. On the other hand, many systems use sudo as root.

Question: how can a script determine whether to use su or sudo without asking the user to enter too many passwords (for example, enter sudo password, if it does not work, run su )).
+6
linux shell su sudo
source share
6 answers

There is no bulletproof way to do this, because any distribution can file files in any way. For example, Debian and Ubuntu often place system files in directories other than Red Hat. It is much easier to configure a script for the OS installed on it.

+3
source share

Do not do it. If the script requires root privileges, it must run as root. This is a business user, how he is going to do it - using su, sudo or some other mechanism.

If you are concerned about security issues and don't want to do everything as root, you can drop the root privileges for these parts.

+6
source share

You can set up an account to not require a password for sudo in / etc / sudoers:

 yourusername ALL=(ALL) NOPASSWD: ALL 

If you do not want to do this, you can force them to run the script as root. Add something like this to the top of the shell script:

 if [ "$UID" -ne 0 ]; then echo "You must be root to run this script" exit 1 fi 

Thus, the user can get root, but choose (su or sudo).

+2
source share

Create another .sh file from this file to call the source .sh file, for example -

 su - oracle /u01/enlightics/Enlightiks/UploadFTP/ExportScript2.sh 
+1
source share

Check if sudo installed

 SU='su' which sudo > /dev/null && SU='sudo' 
0
source share

Although this does not completely answer your question, it is worth noting that you can check if sudo is installed using the following:

Debian based systems:

 dpkg -s sudo 

RPM based systems:

 rpm -q sudo 
0
source share

All Articles