Last active
June 26, 2018 14:03
-
-
Save erplsf/f6299534aa4d07e60a11a8dfa1ca74d8 to your computer and use it in GitHub Desktop.
manage ssh config
This file contains 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
#!/bin/ruby | |
def parse_config(config) | |
hash = {} | |
results = config.scan(REGEXP) | |
results.each do |subarray| | |
hash[subarray[1]] = subarray[2].split("\n").map {|el| | |
ar = el.split | |
[ar.shift, ar.join(' ')]}.inject({}) {|h, a| h[a[0]] = a[1]; h} | |
end | |
hash | |
end | |
def replace(map, name, key, value) | |
map[name][key] = value | |
end | |
def entry_template(name, values_hash) | |
template = "" | |
template << "Host #{name}\n" | |
values_hash.each do |key, value| | |
template << " #{key} #{value}\n" | |
end | |
template << "\n" | |
template | |
end | |
def output(map) | |
string = "" | |
map.each do |name, values_hash| | |
string << entry_template(name, values_hash) | |
end | |
string | |
end | |
SSH_CONFIG_PATH = "~/.ssh/config" | |
REGEXP = /(Host)\s(\S*$)\s(.*?)(?=\1|\Z)/m | |
FILE_PATH = File.expand_path(SSH_CONFIG_PATH) | |
if ARGV.count != 3 | |
raise "Too few arguments" | |
else | |
entry = ARGV[0] | |
key = ARGV[1] | |
value = ARGV[2] | |
config = File.read(FILE_PATH) | |
map = parse_config(config) | |
replace(map, entry, key, value) | |
File.open(FILE_PATH, 'w') do |f| | |
f.write(output(map)) | |
end | |
end | |
# Usage: shatter.rb <entry-name> <key-name> <value-to-replace-with> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment