如何在perlscript中跳转用户,包括root用户?



这个问题在这里以多种形式被问到。我再问一遍,因为所有这些问题都有太多细节。因此,所有的答案都归结为如何解决这些特定的问题,而不会在用户之间跳转。
这就是我为什么把这个问题作为一个新问题(并立即在下面回答)给其他有这个问题的人。

假设您有一个perl脚本,您首先想以root身份运行,然后以普通用户身份运行,然后再以root身份运行。

例如:

#!/usr/bin/perl
#Problem 1: Make sure to start as root
system("whoami");
#Problem 2: Become your regular user
system("whoami");
#Problem 3: Become root again
system("whoami);

应该改成:

root
your_username
root

这是我能想到的最好的解决方案。

如果您想以root用户开始,请先成为普通用户,然后再成为root用户:

#!/usr/bin/perl
use POSIX qw/setuid waitpid/;
exec("sudo", $0, @ARGV) unless($< == 0);  #Restart the program as root if you are a regular user
system("whoami");
my $pid = fork;  #create a extra copy of the program
if($pid == 0) {
#This block will contain code that should run as a regular user
setuid(1000);  #So switch to that user (e.g. the one with UID 1000)
system("whoami");
exit;  #make sure the child stops running once the task for the regular user are done
}
#Everything after this will run in the parent where we are still root
waitpid($pid, 0); #wait until the code of the child has finished
system("whoami");

当以普通用户开始时,最好确保父用户仍然是普通用户,而子用户成为根用户。你可以这样做:

#!/usr/bin/perl
use POSIX qw/setuid waitpid/;
unless($< == 0) {
#regular user code, this is the first code that will run
system("whoami");
#now fork, let the child become root and let the parent wait for the child
my $pid = fork;
exec("sudo", $0, @ARGV) if($pid == 0);
waitpid($pid, 0);
#continue with regular user code, this is the 3th part that will run
system("whoami");
exit; #the end of the program has been reached, exit or we would continue with code meant for root
}
#code for root, this is the 2nd part that will run
system("whoami");


相关内容

最新更新