所以,我一直在研究一個在我的上課期間阻止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的情況下運行腳本?
僅供參考,有一些相當不錯的東西,已經叫做[Self Control](http://selfcontrolapp.com/)。使用一些你不能立即知道如何撤消的東西也可能會更好(因爲你沒有寫)。而這個應用程序的作者非常有創意,防止你繞過它。 –