Skip to content

Instantly share code, notes, and snippets.

@wisq
Created January 14, 2016 19:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wisq/19b0f1757f83f5a6ccac to your computer and use it in GitHub Desktop.
Save wisq/19b0f1757f83f5a6ccac to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'tempfile'
KNOWN_HOSTS = ENV['HOME'] + '/.ssh/known_hosts'
read_fh, write_fh = IO.pipe
command = ['ssh', '-oStrictHostKeyChecking=yes'] + ARGV + ['echo', 'Successful connection.']
fork do
read_fh.close
STDERR.reopen(write_fh)
exec(*command)
end
write_fh.close
lines = read_fh.readlines
lines.each do |line|
if line =~ /^Offending (?:(?:RSA|DSA|ECDSA) key|key for IP) in (.*):(\d+)\r?$/
file, line = $1, $2
raise "Unexpected file: #{file}" unless file == KNOWN_HOSTS
File.open(KNOWN_HOSTS) do |in_fh|
Tempfile.open('known_hosts', File.dirname(KNOWN_HOSTS)) do |out_fh|
lines = in_fh.readlines
lines.delete_at(line.to_i - 1)
out_fh.puts(*lines)
File.rename(KNOWN_HOSTS, KNOWN_HOSTS + '~')
File.rename(out_fh.path, KNOWN_HOSTS)
end
end
puts "Removed key from #{file}, line #{line}."
exec(__FILE__, *ARGV)
end
end
$stderr.puts *lines
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment