Skip to content

Instantly share code, notes, and snippets.

@rosylilly
Created February 28, 2018 06:46
Show Gist options
  • Save rosylilly/13f815684e4de1895c77e39fe4da7d96 to your computer and use it in GitHub Desktop.
Save rosylilly/13f815684e4de1895c77e39fe4da7d96 to your computer and use it in GitHub Desktop.
DNS switcher for macOS
#!/usr/bin/env ruby
require 'optparse'
require 'pathname'
require 'yaml'
VERSION = '0.0.1'
HOMEDIR = Pathname.new(ENV['HOME'])
options = {
config: HOMEDIR.join('.myfi.yml'),
target: 'Wi-Fi', # Check your default service name by `networksetup -listallnetworkservices`
}
optparser = OptionParser.new do |opts|
opts.banner = 'Usage: myfi [options]'
opts.version = VERSION
opts.on('-c CONFIG', '--c CONFIG', 'config file path') do |config|
options[:config] = Pathname.new(config)
end
opts.on('-t TARGET', '--target TARGET', 'Target Network service') do |target|
options[:target] = target
end
opts.on('-a DNS', '--add DNS', 'Add [DNS] set') do |dns|
options[:cmd] = :add
options[:dns] = dns
end
opts.on('-u DNS', '--use DNS', 'Use [DNS] set') do |dns|
options[:cmd] = :set
options[:dns] = dns
end
opts.on('-d', '--default', 'Use default DNS') do |dns|
options[:cmd] = :set
options[:dns] = 'default'
end
opts.on('-l', '--list', 'List DNS group') do |v|
options[:cmd] = :list
end
opts.on('-n', '--now', 'Show current DNS group') do |v|
options[:cmd] = :now
end
opts.on('-v', '--version', 'Show version') do |v|
puts VERSION
exit
end
end
begin
optparser.parse!
rescue OptionParser::ParseError => e
$stderr.puts e.message
exit 1
end
dns_group = {}
dns_group = YAML.load(options[:config].read) if options[:config].exist?
case options[:cmd]
when :add
dns_group[options[:dns]] = ARGV.sort.uniq
options[:config].write YAML.dump(dns_group)
when :set
dns_records = dns_group[options[:dns]] || ['Empty']
system('networksetup', '-setdnsservers', options[:target], *dns_records)
when :list
dns_group.each_pair do |name, records|
puts "* #{name}"
records.each do |record|
puts " - #{record}"
end
puts
end
when :now
records = `networksetup -getdnsservers "#{options[:target]}"`.strip.split("\n").sort
dns_group.each_pair do |name, rrecords|
if rrecords.uniq.sort == records
puts "* #{name}"
exit 0
end
puts "* default"
end
else
$stderr.puts optparser.help
exit 1
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment