Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On Unix, find if user who executed the program is root?

Tags:

I'm writing a rake script and would like to detect (using Ruby rather than bash if possible) if the user who executed the rake script has root privileges.

If it is not root then I would like to terminate the script.

like image 925
ChrisInCambo Avatar asked Mar 13 '09 04:03

ChrisInCambo


People also ask

How do you check if a user is a root user?

The “root” user's UID is always 0 on the Linux systems. Instead of using the UID, you can also match the logged-in user name. The whoami command provides the currently logged user name.

How do I know if a script is running as root?

Check root at start of script Some scripts need to be run as root and you may want to check at the start of that script that it is running as root. This can be done by checking the environment variable $EUID. This variable will hold the value 0 if it's being run as root.

How do I know if user is root or sudo?

Method 2: Check if user is part of the sudo group Another way to find out if a user has sudo access is by checking if the said user is member of the sudo group. If you see the group 'sudo' in the output, the user is a member of the sudo group and it should have sudo access.


2 Answers

Use uid or euid in the Process class:

raise 'Must run as root' unless Process.uid == 0 
like image 153
vladr Avatar answered Sep 25 '22 08:09

vladr


I don't know Ruby, but what you want to check for is if the user ID is 0. In C, you would do this by checking getuid(). From the Unix command line, you could also check the output of id -u.

like image 44
Adam Rosenfield Avatar answered Sep 21 '22 08:09

Adam Rosenfield