2013-07-28 31 views
3

所以,我一直在研究一个在我的上课期间阻止reddit的Ruby脚本(有用的东西)。下面的代码:如何在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 

正如你所看到的,它的动作修改主机从我的文档文件夹到/ etc文件。根据OS X/Unix安全措施,我遇到的问题是我必须通过sudo运行脚本或以root身份登录。这是一个小小的麻烦,但是,我相信这个问题可以在代码中修复。我怎样才能获得超级用户权限,或者通过我的ruby脚本暂时写入对/ etc的访问权限,这样我就可以在不使用sudo/root的情况下运行脚本?

+3

仅供参考,有一些相当不错的东西,已经叫做[Self Control](http://selfcontrolapp.com/)。使用一些你不能立即知道如何撤消的东西也可能会更好(因为你没有写)。而这个应用程序的作者非常有创意,防止你绕过它。 –

回答

-1

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

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

rvmsudo ruby blockreddit.rb 
+0

这是假设@crashfocus正在使用RVM。这个问题上没有标签,也没有任何信息提示这是事实。 – vgoff

+0

我正在使用RVM - 抱歉,我没有提到这一点。但是,我不想使用rvmsudo,我需要在脚本中获得超级用户的东西。 – crashfocus

0

每Unix的安全模型,它是不可能获得没有某种形式的外部干预的root访问权限(setuid的设置为可执行文件,以root身份运行的用户)。否则,我们会有一个巨大的安全漏洞。

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

我只是建议让你所属的组可以写入不同版本的主机文件组。

相关问题