这个问题在这里是以多种形式提出的。我再问一次,因为所有这些问题都有太多的细节。因此,所有的答案都归结为如何解决这些具体的问题,而不是在用户之间跳跃。
这就是我为什么要把这作为一个新的问题(并立即回答下面)给其他有这个问题的人。
假设您有一个perl脚本,在这个脚本中,您首先希望以根用户的身份运行事物,然后以常规用户的身份运行,然后再以根用户的身份运行。
例如:
#!/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发布于 2022-11-09 18:12:42
这是我能想到的最好的解决方案。
如果您想从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");https://stackoverflow.com/questions/74379560
复制相似问题