【问题标题】:How to check for root prvileges from the user in Ruby?如何在 Ruby 中检查用户的 root 权限?
【发布时间】:2018-10-10 19:16:04
【问题描述】:

我正在尝试编写一个需要 root 权限的程序,但无论何时运行它都会引发权限错误。有没有更好的方法以 root 身份运行程序而无需输入sudo 'example_script.rb' 另外,是否有一种方法可以从 ruby​​ 脚本中请求“sudo”或检查用户在使用程序时是否以 sudo 身份运行?谢谢!

【问题讨论】:

    标签: ruby root sudo


    【解决方案1】:

    您可以通过Process.uid查看:

    case (Process.uid)
    when 0
      # We're root!
    else
      $stderr.puts("You must run this with root privileges via sudo")
    end
    

    记住在编写以 root 身份运行的脚本时要格外小心。考虑这样的代码:

    system("convert #{image_path} #{target_path}")
    

    这是一个巨大的安全漏洞,因为没有任何 shell 参数被正确转义。

    更安全的方式:

    system("convert", image_path, target_path)
    

    您需要确保您对任何类型的任何用户数据所做的任何事情,无论您认为自己已多么仔细地筛选这些数据,都会受到极度怀疑。对于任何可以读取或写入文件的操作来说尤其如此。

    【讨论】:

      【解决方案2】:

      最好要求用户以 root 身份或使用sudo 运行脚本,而不是隐式尝试在脚本中获取该权限。这是一种要求用户以 root 身份运行或使用 sudo 运行的方法:

      require 'etc'
      
      if Etc.getpwuid.uid != 0
        puts "You need to run this script as root or using sudo"
        exit 1
      else
        puts "Running in privileged mode"
        # Do stuff only superuser can do
      end
      

      【讨论】:

      • Etc.getpwuid.uidexit 1 是什么意思?
      • Etc.getpwuid 返回当前用户的 /etc/passwd 信息,其中包含用户的 uid。 0 的 uid 分配给 unixy 系统上的 root。 exit 1 向 shell 返回值 1。这表明该命令未成功完成。 0 表示成功。
      • 只是好奇,我将如何在 Windows 上执行此操作?
      猜你喜欢
      • 2011-10-07
      • 2011-01-28
      • 1970-01-01
      • 2018-02-14
      • 2021-10-23
      • 1970-01-01
      • 1970-01-01
      • 2010-12-12
      • 1970-01-01
      相关资源
      最近更新 更多