Running a script with administrator privileges from a standard client terminal

administratorterminal

I have the strong feeling I'm trying to reinvent the wheel, but I did spend some time without finding an existing solution.

I have an already working shell script with several sudos.
Its first target was admin users, so everything was ok.
But now I'm hitting a roadblock for standard users.
Sudo won't work, and as I must run this script on any machine any time, editing sudoers is not an option.

How can I rewrite this script so that it asks for admin user and password once, and then uses this credentials to run as many su as needed? What I'm particularly trying to do is feed password to one-line su but, security risk aside, I've never been able to use something as 'echo | su …', as seen on forums.

Thanks

Best Answer

Generally speaking, you write the script as if an admin will be executing it and you check to see if the user has root privileges to run it. In all of my bash scripts where the script needs root privileges, I have the following code snipit that validates if the user has the correct privileges:

# Validates that user is root; exits if not
echo "Checking Root Privileges"
if [ $(id -u) -ne 0 ]
  then exit 1;
  else echo "User is root";
fi

Basically, all it's doing is checking the UID is 0 for the currently logged in user. You can try it on the command line:

$ id -u                # My login
503

$ sudo id -u           # Root privileges
0

Running the script....

There are a couple of ways you can run the script from a login account that doesn't have admin privileges:

  • add them to the sudoers file or add them to the wheel group
  • add them to a group (besides wheel) that has sudo privileges
  • run the script remotely via ssh with admin credentials
  • run the script as a launchd plist as a Launch Daemon (runs as root)