Running a script with administrator privileges from a standard client terminal

Solution 1:

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)