Running a shell script as root without password prompt

Recently I had a rather daunting task of writing a bash script to update a remote linux box (Ubuntu) via ftp. The person with the linux box needed to execute the script via a desktop launcher. After diving into various forums and blogs, I came up with this solution. Therefore this HOWTO aims to describe how an unprevilaged user can run executables and scripts with the permissions of the owner of the file.

  1. First I made sure the script which was to be run as sudo worked ok. This I just tested it by running the script as a superuser to make sure it works. Here is a sample script which I am going to use for this HOWTO.

    #!/bin/bash
    set -e
    # Remove all previous downloaded packages from package cache directory
    sudo aptitude clean
    exit

  2. Save the script as foo.sh. We then change ownership of the script so that it belongs to root.

    $ sudo chown root:root foo.sh
  3. Various sources claimed that setting the SUID sticky bit on this script would work but it doesn’t. The next step is to make a compiled program to run the script. This compiled executable will then be run by the unprevilaged user. I used C to run the script, here is the c source
    #include <stdio.h>
    #include <stdlib.h>
    #include <sys/types.h>
    #include <unistd.h>
    int main()
    {
    setuid( 0 );
    system("/path/to/your/script/foo.sh");
    return 0;

    }

  4. save the c source file as runfoo.c and with a c compiler like gcc, you can compile it like so,
  5. $ gcc runfoo.c -o bar

  6. gcc is going to spew out an executable named bar which is the file the unprevilaged user is going to execute.
  7. Finally we need to change the ownership and set the SUID to this executable file like so,

    $ sudo chown root:root bar
    $ sudo chmod 4755 bar
    Now the unprevilaged user can execute our bash script without prompt for a password by executing bar which in my case I created a desktop launcher pointing to bar.

Advertisements

3 thoughts on “Running a shell script as root without password prompt

  1. Orang_Gila says:

    Wow! That is so cool, I’ve been hammering this this one for over a day now.
    Thanks!

  2. SAM says:

    Work like charm!!!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: