Reputation: 107
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?
Upvotes: 1
Views: 5889
Reputation: 91
#!/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
Upvotes: 1
Reputation: 839
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
Upvotes: 4