On Unix, find if user who executed the program is

2019-04-03 12:46发布

问题:

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.

回答1:

Use uid or euid in the Process class:

raise 'Must run as root' unless Process.uid == 0


回答2:

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.