The classical UNIX way is making the script setuid:
$ sudo chown root gogui.sh #not necessary if root is already the owner of the file
$ sudo chmod u+s gogui.sh
This will set a special permission bit on the file:
$ ls -l gogui.sh
-rwsr-xr-x 1 root root [omitted] gogui.sh
(Notice the letter s
instead of x
in the fourth position.)
If you do this, all the times you run the script, it will be run with the privileges of the file's owner, instead of the ones of the user that runs it.
You can now simplify your script gogui.sh
to contain only
/usr/sbin/service lightdm start
Notice that I have added an explicit path for the executable (that I have located by typing which service
): this is necessary in setuid files, because otherwise the first program called service
found in your PATH
will be executed. Forgetting the explicit path would be a huge security problem, since it means that any user can tweak the PATH
variable and run a program of their choice with root privileges.
If you wish, you can also restrict other users from running the files with chgrp some_group gogui.sh; chmod o-x gogui.sh
, which will make the file executable only for members of some_group
.
NOPASSWD
syntax detailed insudoers(5)
for password-free calls to that service command, or a suitable wrapper? – thrig Nov 02 '15 at 20:47ps ax
) at just the right time might also see your password. It won't happen in this particular case, asecho
is a bash builtin command, but the general approach is also dangerous for this reason. – marcelm Nov 03 '15 at 16:15