How can I check for root when a user runs a perl script
13,542
Solution 1
If $>
(aka $EFFECTIVE_USER_ID
if you use English
) is non-zero, then the user is not root.
Solution 2
XAppSoftware: How to check for root user has a solution:
my $login = (getpwuid $>);
die "must run as root" if $login ne 'root';
Related videos on Youtube
Author by
ianc1215
Updated on July 14, 2020Comments
-
ianc1215 almost 4 years
I am working a script to generate a config file that I want to store in /etc/solignis. When I run the script as a limited user it does not allow me to create the directory or write the file. So the script will have to run as sudo or a root user, how can I check if the user is a root or atleast using sudo?
-
William Pursell about 13 yearsWhy would you check if the user is root? Just try to create the directory, check if it fails, and then report a message on failure. In other words, the best way to check if you have the correct privileges to do something is to try and do it.
-
-
Arafangion about 13 yearsWilliam Pursell's solution would be even better, though - the user just may well have had root give the necessary privileges to do the task.
-
ianc1215 about 13 yearsOk so 0 is the uid for root or is that the gid?, For a second it did think it would then I realized I made a coding error, it works
-
converter42 about 13 yearsThis answers the poster's question, but the poster is asking the wrong question and has ended up with a non-solution. Open the file. If it fails, report the attempted operation, full pathname and the system error message ($!). There is nothing ambiguous about "Permission denied," which could possibly occur even when the user is root.
-
armannvg over 10 yearsNote that $< will use the userid you are coming from. Therefore, if you do sudo then this will check against the original user but not root. If you want to check against the userid you are going to then use $> (as answered by cjm above). Also for those who want to use die and unless instead you can use: die "This script must be run as root\n" unless $< == 0;