Run shell script as root user (without sudo) using setuid

In the most Linux distributions, setuid doesn’t work on shell scripts because of the security issues associated with it.

But you can use the setuid on binary files and from there you can execute the shell script as root user. And the following steps will help you to do that.

1) Copy the following C program to a file named “runasroot.c” and this program simply runs a script which is passed as command-line argument.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {                                              
  if (argc != 2) {                                                              
    printf("Usage: %s /path/to/script\n", argv[0]);                             
    printf("Note: '/path/to/script' can be either relative or absolute path.\nE\
xamples:\n%s ./ \n%s /tmp/\n", argv[0], argv[0]);                
  } else {                                                                      
    printf("Running the script '%s' as root user...\n", argv[1]);               
   return 0;                                                                    

2) Compile it.

gcc runasroot.c -o runasroot

3) Change the ownership of the compiled executable binary to root

sudo chown root:root runasroot

4) Change the permissions on the binary file with setuid flag

sudo chmod 4755 runasroot

5) Run the script using the executable binary file


Examples :

./runasroot ./ 
./runasroot /tmp/

You can even copy this ‘runasroot’ executable file to your home bin directory (i.e., in ‘/home/user/bin‘) so that you can use it anywhere in your scripts. And you can use the ‘runasroot‘ command (without any password prompt) instead ofsudo‘ in your commands. If you want to pass parameters to the commands, you should use single/double quotes to surround it.

runasroot 'fdisk -l'

instead of

sudo fdisk -l

Warning: Make sure you don’t place this script in any common directory (like /usr/bin or /opt) in a multi-user environments.