Итак, я работал над скриптом Ruby, который блокирует 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
Как вы можете видеть, он перемещает файл измененных хостов из папки «Мои документы» в/etc. Проблема, которую я испытываю, хотя, согласно мерам безопасности OS X/Unix, заключается в том, что я должен запускать скрипт через sudo или регистрироваться как root. Это незначительная неприятность, однако, я считаю, что это может быть исправлено внутри кода. Как я могу получить привилегии суперпользователя, или временно нажимать на/etc на мой рубиновый скрипт, чтобы я мог просто запустить скрипт без sudo/root?
FYI, есть что-то очень хорошее, что уже называется [Self Control] (http://selfcontrolapp.com/). Также может быть лучше использовать то, что вы не сразу знаете, как отменить (потому что вы его не пишете). И автор этого приложения стал довольно креативным, не позволяя вам обойти его. –