Skip to content

Instantly share code, notes, and snippets.

@m-manu
Last active December 28, 2015 07:09
Show Gist options
  • Save m-manu/7462431 to your computer and use it in GitHub Desktop.
Save m-manu/7462431 to your computer and use it in GitHub Desktop.
This script consolidates your "~/.ssh/known_hosts" file. All the aliases and internal/external IP addresses for a node will be merged into one line of the file.
#!/usr/bin/python
import os
import sys
import csv
home = os.getenv("HOME")
known_hosts_path = home+'/.ssh/known_hosts'
known_hosts_optimized_path = home+'/.ssh/known_hosts_optimized'
d = {}
csvfile = open(known_hosts_path, 'r')
khr = csv.reader(csvfile, delimiter=' ')
str_known_hosts_optimized = ""
optimization_count = 0
line_count = 0
for row in khr:
line_count+=1
key = row[2]
hosts = row[0]
method = row[1]
if key in d:
d[key]['hosts'] += "," + hosts
optimization_count+=1
else:
d[key] = {'method':method, 'hosts': hosts}
for k in d:
str_known_hosts_optimized += d[k]['hosts'] + " " + d[k]['method'] + " " + k + "\n"
if optimization_count > 0:
optimizedcsvfile = open(known_hosts_optimized_path, "w")
optimizedcsvfile.write(str_known_hosts_optimized)
optimizedcsvfile.close()
print "File \"%s\" has been optimized.\nDo you wish to overwrite it with optimized version? (y/n): " % (known_hosts_path),
response = sys.stdin.readline()
if response.lower().find("y") >= 0:
os.rename(known_hosts_optimized_path, known_hosts_path)
print "Optimization complete.",
else:
print "Optimized file written to: \"%s\"." % known_hosts_optimized_path,
print " (reduced from %d lines to %d lines)" % (line_count, line_count-optimization_count)
else:
print "Your known_hosts file is already optimized. No action required."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment