如何检查 Ruby 中用户的 root 权限?

How to check for root prvileges from the user in Ruby?

我正在尝试编写一个需要 root 权限的程序,但每当它 运行 时它都会引发权限错误。有没有更好的方法 运行 root 程序而不输入 sudo 'example_script.rb' 另外,是否有可能从 ruby 脚本中请求 `sudo' 或检查是否有用户在使用该程序时 运行ning 是 sudo 吗?谢谢!

您可以通过 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 个参数中的 none 个被正确转义。

更安全的方法:

system("convert", image_path, target_path)

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

最好让用户以 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