Skip to content

Instantly share code, notes, and snippets.

@ilstar
Created June 28, 2014 00:26
Show Gist options
  • Save ilstar/07af1140ae3d8d945ef5 to your computer and use it in GitHub Desktop.
Save ilstar/07af1140ae3d8d945ef5 to your computer and use it in GitHub Desktop.
Update your hosts
#!/usr/bin/ruby
# Usage
# sudo ruby update_hosts.rb
require 'rubygems'
require 'fileutils'
require 'net/http'
LOCAL_HOSTS = "/etc/hosts"
HOSTS_URL = "https://smarthosts.googlecode.com/svn/trunk/hosts"
BEGINNING_IDENTIFIER = "# --- BEGIN HOSTS ---"
def backup
now = Time.now.strftime "%y-%m-%d_%H:%M:%S"
FileUtils.cp LOCAL_HOSTS, "#{LOCAL_HOSTS}.backup.#{now}"
end
def append_hosts
File.open(LOCAL_HOSTS, 'a') do |f|
content = %{#{BEGINNING_IDENTIFIER}\n#{get_hosts}\n}
f.write content
end
end
def remove_old_hosts_if_exists
content = ""
File.open LOCAL_HOSTS, 'r+' do |f|
f.each_line do |line|
break if line.match(/#{BEGINNING_IDENTIFIER}/)
content += line
end
end
File.open LOCAL_HOSTS, 'w' do |f|
f.write content
end
end
def get_hosts
return Net::HTTP.get(URI.parse HOSTS_URL)
end
def main
backup
remove_old_hosts_if_exists
append_hosts
end
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment