Writing scripts that needs root permission
September 2nd, 2007 mysurface Posted in Admin, Bash, sudo | Hits: 33599 |
While executing commands that needs root permission, I rely on sudo. Sudo provides me a very convenient way to execute root privilege commands from my user account provided with my user account password.
Sudo and su are not the same, check out more from here.
When comes to scripting, I couldn’t use sudo directly. For examples I make up a script modifying /etc/resolv.conf with my DNS settings. In order to modify /etc/resolv.conf, I need root permission. But I couldn’t execute commands directly with sudo in the script.
Below showing the script that DOES NOT work.
#!/bin/bash
# the lines below doesn't work!!!
sudo echo "nameserver 202.188.1.5" > /etc/resolv.conf
sudo echo "nameserver 202.188.0.133" >> /etc/resolv.conf
cat /etc/resolv.conf
I can write all our commands that need root permission in the script, then externally execute the script with sudo. Let say my script is set_dns.sh.
sudo ./set_dns.sh
The line above works! But what if I want to run it as normal user and it prompts me for sudo password? I figure out a way, I can do that with the script below.
#!/bin/bash
if [ "$1" == 'done' ]
then
#the commands needs root permission list as below
echo "nameserver 202.188.1.5" > /etc/resolv.conf
echo "nameserver 202.188.0.133" >> /etc/resolv.conf
cat /etc/resolv.conf
else
sudo $0 done
fi
I make it as a template, I just have to replace the portion between ‘then’ and ‘else’.
[䏿–‡ç¿»è¯‘ï¼½
Live Chat!







October 4th, 2007 at 4:11 am
But you can’t use parameters with your script!
If you use this it will work:
if [ "$1" == 'done' ]; then
shift
# …
else
sudo $0 done $*
fi
November 3rd, 2007 at 8:24 pm
Interesting, and cool! I’ve been enabling sudo to run without a password by adding this line to the /etc/sudoers file:
bbjones ALL=NOPASSWD: ALL
and that makes adding to su to scripts and desktop shortcuts pretty straightforward. Of course, some users aren’t going to want to run sudo without a password for security reasons.
April 10th, 2008 at 8:59 am
me I use temp files and than sudo cp, I find it easier to manage
By example this simple script to set minimum fan speed on macbooks:
echo “Input desired minimum speed (in RPM):”
read speed
echo $speed > ./.tmp
sudo cp ./.tmp /sys/devices/platform/applesmc.768/fan1_min -f
rm ./.tmp