我正在尝试编写一个需要root权限的程序,但每次运行时都会引发权限错误。有没有更好的方法可以以root身份运行程序而无需输入sudo 'example_script.rb'
?此外,是否可能从ruby脚本内请求`sudo'或检查用户在使用程序时是否作为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参数进行适当的转义。
更安全的方式:
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
Etc.getpwuid.uid
和exit 1
是什么意思? - Practical1Etc.getpwuid
返回当前用户的 /etc/passwd 信息,其中包含用户的 uid。在 Unix 系统上,uid 0 被分配给 root 用户。exit 1
将值 1 返回给 shell。这表示命令未成功完成。0 表示成功。 - Mike Gorski