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?
- 1You might get better responses over at superuser.JavaKungFu– JavaKungFu2012-04-22 20:42:31 +00:00Commented Apr 22, 2012 at 20:42
- easy, launch a browser with a known security breach and gain root accessCharlesB– CharlesB2012-04-22 21:14:19 +00:00Commented Apr 22, 2012 at 21:14
2 Answers
#!/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