class Object

Public Instance Methods

ask_user() click to toggle source
# File lib/ssh_keys.rb, line 21
def ask_user
  $stdin.gets.to_s.strip
end
error(message) click to toggle source
# File lib/ssh_keys.rb, line 25
def error(message)
  $stderr.puts(message)
  exit(1)
end
generate_ssh_key(keyfile) click to toggle source
# File lib/ssh_keys.rb, line 8
def generate_ssh_key(keyfile)
  ssh_dir = File.join(home_directory, ".ssh")
  unless File.exists?(ssh_dir)
    FileUtils.mkdir_p ssh_dir
    File.chmod(0700, ssh_dir)
  end
  `ssh-keygen -t rsa -N "" -f \"#{home_directory}}/.ssh/#{keyfile}\" 2>&1`
end
get_key(key) click to toggle source
# File lib/ssh_keys.rb, line 17
def get_key(key)
  File.read(key).chomp #strip trailing newline if present
end
get_or_generate_ssh_key() click to toggle source
# File lib/ssh_keys.rb, line 38
def get_or_generate_ssh_key
  public_keys = Dir.glob("#{home_directory}/.ssh/*.pub").sort

  case public_keys.length
  when 0 then
    puts "Could not find an existing public key."
    puts "Let's generate one..."
    puts "Generating new SSH public key."
    generate_ssh_key("id_rsa")
    get_key("#{home_directory}/.ssh/id_rsa.pub")
  when 1 then
    puts "Using existing public key: #{public_keys.first}"
    get_key(public_keys.first)
  else
    puts "Found the following SSH public keys:"
    public_keys.each_with_index do |key, index|
      puts "#{index+1}) #{File.basename(key)}"
    end
    puts "Which would you like to use? (Enter number) "
    choice = ask_user.to_i - 1
    chosen = public_keys[choice]
    if choice == -1 || chosen.nil?
      error("Invalid choice.")
    end
    get_key(chosen)
  end
end
home_directory() click to toggle source
# File lib/ssh_keys.rb, line 30
def home_directory
  running_on_windows? ? ENV['USERPROFILE'].gsub("\\","/") : ENV['HOME']
end
running_on_windows?() click to toggle source
# File lib/ssh_keys.rb, line 34
def running_on_windows?
  RUBY_PLATFORM =~ /mswin32|mingw32/
end