Skip to content

Instantly share code, notes, and snippets.

@dacort
Created July 22, 2010 19:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dacort/486442 to your computer and use it in GitHub Desktop.
Save dacort/486442 to your computer and use it in GitHub Desktop.
# In here, we monkey-patch Net::SSH. Beware, there be dragons.
# Net::SSH can add hosts to the known_hosts file, but can't remove
module Net; module SSH
class KnownHosts
# Looks in all user known host files (see KnownHosts.hostfiles) and tries to
# remove an entry for the given host and key to the first file it is able to.
def self.remove(host, options={})
hostfiles(options, :user).each do |file|
begin
KnownHosts.new(file).remove(host)
return
rescue SystemCallError
# try the next hostfile
end
end
end
# Tries to delete an entry from the current source file for the given host
# If it is unable to (because the file is not writable, for instance),
# an exception will be raised.
def remove(host)
keys = File.readlines(source)
keys.delete_if{|host_info| host_info.split[0] == host}
File.open(source, "w") do |f|
keys.each{|line| f.puts(line)}
end
end
end
end; end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment