Linux – Execute a script which needs root privileges using SUDO command

By | November 7, 2013

Linux – usage of SUDO command to execute a script with ROOT privileges

A user with sudo privilege can execute a script which needs root privileges. For example, I have a very simple script that lists the files inside a folder “test” in the /root directory. Obviously that needs root privileges.

#putting some files to the testing location

root@vps[/usr/local/src/testleo]# touch /root/test/{a..z}.txt

#setting up test script

root@vps[/usr/local/src/testleo]# cat script.sh
#/bin/sh
ls -l /root/test/;
root@vps[/usr/local/src/testleo]# chmod +x script.sh
root@vps[/usr/local/src/testleo]#

I am now creating a test user and trying to execute it.

#testing with test user

root@vps [/usr/local/src/testleo]# useradd testleo
root@vps [/usr/local/src/testleo]# su testleo
testleo@vps [/usr/local/src/testleo]# ls
./  ../  script.sh*
testleo@vps[/usr/local/src/testleo]# sudo ./script.sh
[sudo] password for testleo:
testleo is not in the sudoers file.  This incident will be reported.
testleo@vps[/usr/local/src/testleo]#

Now we needed to give sudo permission for this user to execute this script only.

Give write permission to /etc/sudoers

#giving sudo permission

root@vps[/usr/local/src/testleo]# chmod +w /etc/sudoers
root@vps[/usr/local/src/testleo]# echo ‘testleo ALL=(ALL)  NOPASSWD:/usr/local/src/testleo/script.sh’ >> /etc/sudoers
root@vps[/usr/local/src/testleo]# chmod -w /etc/sudoers

#testing with sudo test user

root@vps[/usr/local/src/testleo]# su testleo
testleo@vps[/usr/local/src/testleo]# sudo ./script.sh
total 0
-rw-r–r– 1 root root 0 Nov  7 14:10 a.txt
-rw-r–r– 1 root root 0 Nov  7 14:10 b.txt
-rw-r–r– 1 root root 0 Nov  7 14:10 c.txt
-rw-r–r– 1 root root 0 Nov  7 14:10 d.txt
-rw-r–r– 1 root root 0 Nov  7 14:10 e.txt
-rw-r–r– 1 root root 0 Nov  7 14:10 f.txt
-rw-r–r– 1 root root 0 Nov  7 14:10 g.txt
-rw-r–r– 1 root root 0 Nov  7 14:10 h.txt
-rw-r–r– 1 root root 0 Nov  7 14:10 i.txt
-rw-r–r– 1 root root 0 Nov  7 14:10 j.txt
-rw-r–r– 1 root root 0 Nov  7 14:10 k.txt
-rw-r–r– 1 root root 0 Nov  7 14:10 l.txt
-rw-r–r– 1 root root 0 Nov  7 14:10 m.txt
-rw-r–r– 1 root root 0 Nov  7 14:10 n.txt
-rw-r–r– 1 root root 0 Nov  7 14:10 o.txt
-rw-r–r– 1 root root 0 Nov  7 14:10 p.txt
-rw-r–r– 1 root root 0 Nov  7 14:10 q.txt
-rw-r–r– 1 root root 0 Nov  7 14:10 r.txt
-rw-r–r– 1 root root 0 Nov  7 14:10 s.txt
-rw-r–r– 1 root root 0 Nov  7 14:10 t.txt
-rw-r–r– 1 root root 0 Nov  7 14:10 u.txt
-rw-r–r– 1 root root 0 Nov  7 14:10 v.txt
-rw-r–r– 1 root root 0 Nov  7 14:10 w.txt
-rw-r–r– 1 root root 0 Nov  7 14:10 x.txt
-rw-r–r– 1 root root 0 Nov  7 14:10 y.txt
-rw-r–r– 1 root root 0 Nov  7 14:10 z.txt
testleo@vps[/usr/local/src/testleo]#

The points to be noted are

1, Make sure you have provided the complete path of the script in the /etc/sudoer file

2, Revert the permission of /etc/sudoers file 0440 after writing the required lines.

Happy days ahead. :)