Search code examples
unixrootsudoadministratorsu

Changing unix user in a shell script


I want to change the current user in a shell script in order to give the user the ability to execute the commands as an administrator, by passing the login and password as arguments.

I want to have the ability to do something like :

sh ./script.sh login password

And inside the script, something like :

sudo $1 $2 etc...

However I can't figure out how to clearly code this.

Thanks for any help


Solution

  • Just Use Sudo

    The sudoers(5) file allows for very complex permissions and command specifications. As a simplistic example, you can just let everyone in a group run a single script as root without the need for a password. This is much more scriptable, while still allowing you to limit access. For example:

    # /etc/sudoers
    %somegroup ALL=(ALL:ALL) NOPASSWD:/path/to/script.sh
    

    Since the script will run as root by default, no further hoops need to be jumped through in your script.

    Note on Topicality

    This is somewhat on-topic for Stack Overflow, since it's scripting-related. However, if you have follow-on questions about configuring the sudoers file, you should probably ask those questions on SuperUser instead.