Created
September 30, 2015 10:47
-
-
Save paaloeye/180eaf5fc0422fb06f98 to your computer and use it in GitHub Desktop.
Tool for /etc/hosts update
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'resolv' | |
# Alter /etc/hosts leveraging Augeus | |
# 1. Find /files/etc/hosts/$x/canonical with needed | |
# | | |
# |---- Found: 2.1 Check ip | |
# | | |
# |---- Not found: 2.2 Create node | |
node_start = 1 | |
node_end = 100 | |
dns_source = '10.0.10.2' | |
augtool_cmd = "augtool -L" | |
resolv_db = {} | |
resolver = Resolv::DNS.new(:nameserver => dns_source) | |
flag_file_updated = false | |
# Make resolvdb | |
node_start.upto(node_end).each do |num| | |
name = "node-#{num}.domain.tld" | |
result = resolver.getaddresses(name) | |
unless result.empty? | |
node = resolv_db[name] = {} | |
node[:ip] = result.first | |
IO.popen(augtool_cmd,'r+') do |io| | |
io.puts("match /files/etc/hosts/*/canonical[. = '#{name}']") | |
io.close_write | |
result = io.read | |
end | |
if result =~ /no matches/ | |
node[:new] = true | |
else | |
IO.popen(augtool_cmd, 'r+') do |io| | |
io.puts("match /files/etc/hosts/*[canonical = '#{name}'][ipaddr = '#{node[:ip]}']") | |
io.close_write | |
result = io.read | |
if result =~ /no matches/ | |
node[:new] = true | |
end | |
end | |
end | |
end | |
end | |
IO.popen(augtool_cmd,'r+') do |io| | |
# Create new entries | |
resolv_db.select { |name, opts| opts[:new] }.each.with_index do |entry,index| | |
flag_file_updated = true unless flag_file_updated | |
name, opts = entry | |
io.puts <<-AUG | |
set /files/etc/hosts/0#{index+1}/ipaddr #{opts[:ip]} | |
set /files/etc/hosts/0#{index+1}/canonical #{name} | |
AUG | |
end | |
# Update out of sync entries | |
resolv_db.select { |name, opts| opts[:dirty] }.each.with_index do |entry,index| | |
flag_file_updated = true unless flag_file_updated | |
name, opts = entry | |
io.puts <<-AUG | |
set /files/etc/hosts/*[canonical = '#{name}']/ipaddr #{opts[:ip]} | |
AUG | |
end | |
io.puts("save") | |
io.close_write | |
end | |
if flag_file_updated | |
puts "DEBUG: Host file was updated" | |
else | |
puts "DEBUG: Host file is up to date" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment