如何在Ruby中获得超级用户权限?

时间:2013-07-28 01:41:18

标签: ruby root sudo setuid

所以,我一直在研究一个在我上课时间阻止reddit的Ruby脚本(有用的东西)。这是代码:

require 'fileutils'

puts "-----------------------------------"
puts "Welcome to the hosts file modifier!"
puts "-----------------------------------"
puts "Option A: Use modified hosts"
puts "Option B: Use original hosts"
puts "Option C: Do nothing"
puts "Please enter your choice: "
input = gets.chomp.downcase

t = Time.now
# Time.now is used is conjunction with function 'original', in option 'b'

def modified
  # This function copies the modified (redditblocking) hosts file from Documents to /etc
  puts "Moving original hosts file out of /etc"
  FileUtils.mv('/etc/hosts', '/Users/(usernameobscured)/Documents/OriginalHosts/hosts')
  puts "Done. Now copying modified hosts to /etc"
  FileUtils.cp('/Users/(usernameobscured)/Documents/ModifiedHosts/hosts', '/etc/hosts')
  puts "Done"
end

def original
# This function deletes the modified hosts file from /etc (since we have a copy in Documents)
# and then moves the original hosts file back to /etc
  puts "Deleting modified hosts file from /etc"
  FileUtils.rm_rf('etc/hosts')
  puts "Done. Now copying original hosts to /etc"
  FileUtils.mv('/Users/(usernameobscured)/Documents/OriginalHosts/hosts', '/etc/hosts')
  puts "Done"
end

def nothing
  # This does... nothing. Literally.
  puts "Doing nothing"
end

if input == 'a'
  modified
end

if input == 'b'
  # Here's when using Time.now becomes helpful: if the hour of the day is less than 5PM,
  # then the original hosts file can't be moved back (don't wanna be on reddit during school hours!)
  if t.hour > 17
    original
  elsif t.hour < 17
    puts "Too early to use original hosts file. Come back at 5PM"
  end
end

if input == 'c'
  # Nothing...
  nothing
end

如您所见,它将修改后的hosts文件从我的Documents文件夹移动到/ etc。根据OS X / Unix安全措施,我遇到的问题是我必须通过sudo运行脚本或以root身份登录。这是一个小麻烦,但是,我相信它可以在代码中修复。如何通过我的ruby脚本获得超级用户权限,或临时写入/ etc访问权限,以便我可以简单地运行没有sudo / root的脚本?

2 个答案:

答案 0 :(得分:0)

根据Unix安全模型,如果没有某种外部干预(setuid设置为可执行文件,以root用户身份运行),则无法获得root访问权限。否则我们会有一个巨大的安全漏洞。

我不清楚您使用sudorvmsudo或设置脚本setuid的问题究竟是什么(可以将sudo配置为不需要密码来定义狭义的集合命令)。

我建议您使用您所属的群组,使各种版本的主机文件组可写。

答案 1 :(得分:-1)

根据此网站:http://ruby.about.com/od/rubyversionmanager/qt/Rvm-And-Sudo.htm

您可以使用rvmsudo命令开始执行脚本。在终端窗口或shell脚本中:

rvmsudo ruby blockreddit.rb