Skip to content

Instantly share code, notes, and snippets.

@lastobelus
Created January 26, 2009 06:26
Show Gist options
  • Save lastobelus/52725 to your computer and use it in GitHub Desktop.
Save lastobelus/52725 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'rubygems'
require 'highline'
require 'yaml'
ENV['HOME']
user_name = ARGV[1] || 'root'
key_name = ARGV[2]
valid_host_regex = /ec\d+-\d{1,3}-\d{1,3}-\d{1,3}-\d{1,3}(\..*)?/
ssh_dir = "#{ENV['HOME']}/.ssh/"
keys = Dir.glob("#{ssh_dir}id_r*").reject{|p| p =~ /\.pub$/}
key_names = keys.map{|k| k.sub(ssh_dir, '')}
key = key_names.detect{|k| k =~ /id_rsa-#{key_name}/} if key_name
ui = HighLine.new
host = ARGV[0]
known_hosts_file = File.dirname(__FILE__)+'/.known_ec2_hosts'
if File.exists?(known_hosts_file)
known_hosts = YAML::load_file(known_hosts_file)
else
known_hosts = {}
end
available_hosts = known_hosts.keys
if host.nil? || (host == "") || !(host =~ valid_host_regex)
available_hosts << "enter new"
ui.say(ui.color('Choose a host:',HighLine::BOLD))
host = ui.choose(*available_hosts)
end
if (host == "enter new")
host = ui.ask("ok, enter a host: ") { |q| q.validate = valid_host_regex }
end
case host.count('.')
when 0
host += ".compute-1.amazonaws.com"
when 1
host += ".amazonaws.com"
when 2
host += ".com"
end
key = known_hosts[host]
unless key
if key_names.length > 1
ui.say(ui.color('Choose a key:',HighLine::BOLD))
key = ui.choose(*key_names)
else
key = key_names.first
end
end
known_hosts[host] = key
File.open(known_hosts_file, "w") { |f|
YAML.dump(known_hosts, f)
}
key_path = "#{ssh_dir}#{key}"
Dir.chdir("/Users/lasto/.ssh")
ssh_known_hosts = File.read("known_hosts")
ssh_known_hosts.gsub!(/^[^\n]*#{host}[^\n]*$\n?/, '')
File.open("known_hosts", 'w'){|f| f.write ssh_known_hosts}
login = "#{user_name}@#{host}"
cmd = "ssh -i #{key_path} #{login}"
puts cmd
Kernel.exec cmd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment