Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

What is the best way to find username running your script?

by dr.jekyllandme (Sexton)
on Nov 21, 2012 at 20:11 UTC ( #1004999=perlquestion: print w/ replies, xml ) Need Help??
dr.jekyllandme has asked for the wisdom of the Perl Monks concerning the following question:

Hello, I am writing a script that will find which user is executing the script. I found 3 different ways to do this:
#!usr/bin/perl use strict; use warnings; my $logname = $ENV{ LOGNAME }; print "\$logname = $logname\n"; my $user = $ENV{ USER }; print "\$user = $user\n"; my $pwuid = getpwuid( $< ); print "\$pwuid = $pwuid\n";
I noticed that for $ENV{ LOGNAME } and $ENV{ USER }, I can changes the variable value using setenv in csh and export in bash. But getpwuid's value always gives me the correct value. So should I go with getpwuid to get the correct user that is calling the script? Is there a better way? Thank you.

Comment on What is the best way to find username running your script?
Download Code
Re: What is the best way to find username running your script?
by tobyink (Abbot) on Nov 21, 2012 at 20:14 UTC
    my $username = getpwuid($<);

    Not sure how well it does on MSWin32.

    perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
Re: What is the best way to find username running your script? (Windows)
by tye (Cardinal) on Nov 21, 2012 at 20:44 UTC

    I use $ENV{USERNAME} because it works on Unix and on Windows, IME. $ENV{LOGNAME} is probably the oldest one on the Unix side and so may be the most widely supported. You can even use something like $ENV{LOGNAME} || $ENV{USERNAME} || $ENV{USER} (assuming you don't let anybody have a username of "0").

    Of course, if you are worried about preventing people from pretending to be somebody else, then you shouldn't rely on an environment variable.

    - tye        

Re: What is the best way to find username running your script?
by Anonymous Monk on Nov 22, 2012 at 04:18 UTC

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1004999]
Approved by tobyink
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (6)
As of 2014-12-20 10:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (95 votes), past polls