Often, during my work, I must check for the user that is launching my applications, specifically some applications like ping/shutdown/../.. need to be executed by root user.
I collected four pieces of code in four languages
Ruby
raise 'Must run as root' unless Process.uid == 0
C
if(getuid()!=0)
{
printf("You must be root to run this app\n");
exit(EXIT_FAILURE);
}
bash
if [ "$(id -u)" != "0" ]; then
echo "This script must be run as root" 1>&2
exit 1
fi
perl
$login = (getpwuid($>)); if (!$login == "root") { die "\nYou cannot run this Perl script as user \"$login\", must be ROOT!\n\n"; }
As suggested by Renée there was a bug so use the following:
my $login = (getpwuid $>);
die "must run as root" if $login ne 'root';
Gg1
Your Perl code is buggy:
you get the login name and then you negate it (!$login). If you negate a string you get “” (empty string).
Then you use “==” and that forces a numeric context. Strings in numeric context is a bit weird (at least for Perl beginners): If there is a number at the beginning of the string, that number is used ( “34test” => 34, “24test23” => 24). But neither the empty string nor the string “root” has a number at the beginning. So the second rule is taken: Without the number at the start, Perl uses 0 (“root” => 0, “test23” => 0).
So your comparison is 0 == 0 and that’s always true.
If you want to compare strings, you have to use
eq => ‘root’ eq ‘root’ => 1; ‘root’ eq ‘test’ => 0
ne => ‘root’ ne ‘root’ => 0; ‘root’ ne ‘test’ => 1
lt, gt, le, ge,…
In Perl you could use:
my $login = (getpwuid $>);
die “must run as root” if $login ne ‘root;
or simply
die “must run as root” if $> != 0;
Thak you very much for your post.
You should have taken the last one-liner for Perl, as it does the same as the snippets in the other languages (ie checking for uid == 0) 🙂
This makes it so clear that Perl rules. 😉