Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

su and sudo in a shell script

Tags:

linux

shell

sudo

su

There is a shell script (/bin/sh, not bash) that requires root permissions for execution.

If it is ran by a normal user it should ask user a password to get root access and re-run itself.

Now it uses the following code:

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

That works fine, but there are some OS like Ubuntu that has no root password at all. On the other hand, a lot of systems use sudo for root permissions.

The question is: how can the script detect whether to use su or sudo without asking the user to enter too much passwords (e.g. enter sudo password, if it fails - run su).

like image 969
zserge Avatar asked Oct 04 '10 15:10

zserge


1 Answers

It shouldn't. If script requires root privileges, it should be run as root. It's the user's business how he's going to accomplish that -- using su, sudo or some other mechanism.

If you are concerned with security issues and don't want to do everything from root, you can drop root privileges for those parts.

like image 138
Roman Cheplyaka Avatar answered Oct 03 '22 21:10

Roman Cheplyaka