Skip to content

Instantly share code, notes, and snippets.

@dstrelau
Created February 5, 2009 22:24
Show Gist options
  • Save dstrelau/59057 to your computer and use it in GitHub Desktop.
Save dstrelau/59057 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'rubygems'
require 'thor'
class Dscl < Thor
map "-l" => :list, "-a" => :create, "-d" => :delete
desc "list", "list known hosts"
def list
raw = `sudo dscl localhost -readall /Local/Default/Hosts`.split('-')
out = raw.inject(Hash.new {|hash,k| hash[k]=[]}) do |hosts, entry|
entry =~ /IPAddress: (.*)\nRecordName: (.*)/
hosts[$1] << $2 unless $1.nil? or $2.nil?
hosts
end
out.each do |ip,hosts|
puts ip
puts "=" * ip.length
hosts.each {|h| puts h }
puts
end
end
desc "create HOST [IP=127.0.0.1]", "add a host"
def create(host, ip='127.0.0.1')
`sudo dscl localhost -create /Local/Default/Hosts/#{host} IPAddress #{ip}`
end
alias_method :add, :create
desc "delete HOST", "remove a host"
def delete(host)
`sudo dscl localhost -delete /Local/Default/Hosts/#{host}`
end
alias_method :remove, :delete
end
Dscl.start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment