這個問題已在此處以多種形式提出。我再問一次,因為所有這些問題都有太多細節。因此,答案都歸結為如何解決這些特定問題,而無需在用戶之間跳轉。
這就是我為什么將其作為一個新問題發布(并在下面立即回答),以供其他有此問題的人使用。
假設您有一個以 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
uj5u.com熱心網友回復:
這是我能想到的最好的解決方案。
如果您想以 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");
以普通用戶身份開始時,最好確保父母保持普通用戶身份,而孩子成為 root 用戶。你可以這樣做:
#!/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://www.uj5u.com/shujuku/533316.html
標籤:perl须藤苏设置
