Created
January 14, 2016 19:31
-
-
Save wisq/19b0f1757f83f5a6ccac to your computer and use it in GitHub Desktop.
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
#!/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