Skip to content

Instantly share code, notes, and snippets.

@chrisyip
Last active Dec 24, 2015
Embed
What would you like to do?
a command line tool to help add / delete / list / search hosts file.
#!/usr/bin/env ruby
# encoding: utf-8
require 'optparse'
require 'fileutils'
@options = {}
@hosts_path = '/private/etc/hosts'
OptionParser.new { |opts|
opts.banner = 'Usage: [options]'
opts.on('-a', '--add domain', 'domain will be added') do |domain|
@options[:method] = 'add'
@options[:domain] = domain
end
opts.on('-d', '--del domain', 'domain will be deleted') do |domain|
@options[:method] = 'del'
@options[:domain] = domain
end
opts.on('-i', '--ip ip', 'ip. if missing when adding domain, will be 127.0.0.1; if presented when deleting domain, only the domain that macthes this ip will be deleted') do |ip|
@options[:ip] = ip
end
opts.on('-l', '--list [keyword]', 'list of domains and ip that matches search keyword') do |keyword|
@options[:search] = true
@options[:keyword] = keyword
end
opts.on_tail('-h', '--help', 'list of arguments') do
puts opts
exit
end
opts.parse!
}
def manipulation (ip, domain, method)
contents = File.read @hosts_path
if method == 'add'
ip ||= '127.0.0.1'
File.open(@hosts_path, "a:UTF-8") do |file|
domain.split(' ').each do |d|
file.puts ip + ' ' + d + "\n"
puts "#{ip} is added to #{d}."
end
end
else
new_contents = []
domains = domain.split(' ').join('|')
re = nil
re_str = "(#{domains})"
re_str = "#{ip}\s+" + re_str if ip
re_str.gsub! '.', '\.'
re = /#{re_str}/
contents.each_line do |line|
new_contents.push(line) unless re.match line
end
File.open(@hosts_path, "w:UTF-8") do |file|
file.truncate 0
file.write new_contents.join
end
puts "#{domain} is/are deleted."
end
end
def list (keyword)
File.open(@hosts_path, "r:UTF-8") do |file|
file.read.each_line do |line|
puts line if line.index keyword.to_s
end
end
end
if @options[:search]
list @options[:keyword]
else
manipulation @options[:ip], @options[:domain], @options[:method]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment