Question

I'm trying to have a script run as root that adds directories and changes permissions, but I'm not sure how to have it run as root without prompting the user for a password. The user is not necessarily a sudoer, so doing any kind of sudo -S command or changing sudoer preferences to not require a password won't work here. Any ideas?

Était-ce utile?

La solution

Sudo is your friend. Configure /etc/sudoers to allow anyone to run the script at a particular location, eg:

ALL   ALL = NOPASSWD: /path/to/my/root/script

Autres conseils

#!/bin/bash

#Example of a Linux script executing instruction(s) as super user from Graphic User Interface (Ubuntu GUI desktop)

#These two instructions only for this example which change to root ownership a given file

#Change this script to executable if not already done

echo $0 | chmod ugo+x

#Create a file for this specific example

echo "some text" > ./my_file

#

#Executing the root instruction, useful for custom startup scripts launched at ubuntu login for example

#Pop up box for asking password

PASSWD=zenity --entry --text "Enter root password" --hide-text

#Execute an action as superuser

sudo -S su root -c "chown root ./my_file" <<< "$PASSWD"

#

#Following actions only for this specific example

# Display file ownership to check file belongs to root

printf $'\n'; ls -al ./my_file; printf $'\n'

#Restore current user ownership if necessary

sudo -S su root -c "chown `whoami` ./my_file" <<< "$PASSWD"

#Display file ownership again to check if it belongs back to current user

printf $'\n'; ls -al ./my_file; printf $'\n'

#Clear cache for prompting again password if this terminal session is not closed

sudo -k
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top