首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在用户(包括root用户)之间跳转到perlscript中?

如何在用户(包括root用户)之间跳转到perlscript中?
EN

Stack Overflow用户
提问于 2022-11-09 18:12:42
回答 1查看 53关注 0票数 0

这个问题在这里是以多种形式提出的。我再问一次,因为所有这些问题都有太多的细节。因此,所有的答案都归结为如何解决这些具体的问题,而不是在用户之间跳跃。

这就是我为什么要把这作为一个新的问题(并立即回答下面)给其他有这个问题的人。

假设您有一个perl脚本,在这个脚本中,您首先希望以根用户的身份运行事物,然后以常规用户的身份运行,然后再以根用户的身份运行。

例如:

代码语言:javascript
复制
#!/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);

应更改为显示:

代码语言:javascript
复制
root
your_username
root
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-11-09 18:12:42

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

如果您想从root开始,那么成为一个常规用户,然后再次成为root用户:

代码语言:javascript
复制
#!/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");

当作为常规用户启动时,最好确保父用户保持常规用户,并确保子用户成为根用户。你可以这样做:

代码语言:javascript
复制
#!/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");
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74379560

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档