问题描述
有一个需要以root用户身份运行的perl脚本,但是我们必须确保运行该脚本的用户最初并未以用户"foo"的身份登录,因为在脚本执行期间该用户将被删除.
There is a perl script that needs to run as root but we must make sure the user who runs the script did not log-in originally as user 'foo' as it will be removed during the script.
那么,如何确定自登录后可能已经起诉过几次的用户在该链中的任何时候都没有假冒'foo'?
So how can I find out if the user, who might have su-ed several times since she logged in has not impersonated 'foo' at any time in that chain?
我发现了一个有趣的perl脚本,该脚本正在调用以下两个shell脚本,但是我认为这仅在Solaris上有效.
I found an interesting perl script that was calling the following two shell scripts, but I think that would only work on Solaris.
my $shell_parent =
`ps -ef | grep -v grep | awk \'{print \$2\" \"\$3}\' | egrep \"^@_\" | awk \'{print \$2}'`;
my $parent_owner =
`ps -ef | grep -v grep | awk \'{print \$1\" \"\$2}\' | grep @_ | awk \'{print \$1}\'`;
这需要在Linux和Solaris上都可以使用,我宁愿消除对shell的重复调用,并将整个内容保留在Perl中.
This needs to work on both Linux and Solaris and I'd rather eliminate the repeated calls to he the shell and keep the whole thing in Perl.
推荐答案
又快又脏(仅限UNIX):
Quick and dirty and (UNIX only):
my $user = (split /\s/,`who am i`)[0];
我是谁
命令返回TTY的所有者-即您登录时的身份.
The who am i
command returns the owner of the TTY - i.e. who you were when you logged in.
如果要在纯perl中执行此操作:
If you want to do this in pure perl:
use POSIX;
my $tty = POSIX::ttyname(1); # The tty we are running in
my $uid = (stat $tty)[4]; # The owner uid of that tty
my $user = getpwuid($uid); # The user with that uid
即使有多个su,它也会返回正确的用户.这通常会使您(经验不足的)系统管理员感到吃惊.
This will return the correct user, even after multiple su's. This usually freaks out your (less experienced) sysadmins.
这篇关于如何查找开始流程的原始用户名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!