Guest User

Untitled

a guest
Jun 16th, 2018
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.43 KB | None | 0 0
  1. namespace :ssh do
  2. desc "Install your public key on a remote server."
  3. task :install_public_key do
  4. begin
  5. require 'rubygems'
  6. require 'net/ssh'
  7. require 'net/scp'
  8. require 'highline'
  9. rescue LoadError
  10. abort "There was a problem loading net-ssh, net-scp, or highline. Please make sure you have them installed via RubyGems."
  11. end
  12.  
  13. public_key = if ENV["public_key_path"]
  14. if File.exists?(ENV["public_key_path"]) then ENV["public_key_path"]
  15. else abort "The key you provided via the command line does not exist!"
  16. end
  17. else
  18. discovered_key = %w[id_rsa id_dsa identity].map { |f| "#{ENV['HOME']}/.ssh/#{f}.pub" }.detect { |f| File.exists?(f) }
  19. if discovered_key then discovered_key
  20. else abort <<-EOS
  21. I wasn't able to discover your public key. I tried to find id_rsa.pub, id_dsa.pub,
  22. or identity.pub in "#{ENV['HOME']}/.ssh". You can hard code the path to the file by
  23. passing public_key_path via the command line.
  24. EOS
  25. end
  26. end
  27.  
  28. h = HighLine.new
  29. not_blank = Proc.new { |s| !s.empty? }
  30. def not_blank.to_s; "not blank"; end
  31.  
  32. h.say "I need some information to SSH into the server."
  33. hostname = h.ask("Remote Hostname: ") { |q| q.validate = not_blank }
  34. port = h.ask("Remote port: ") { |q| q.default = 22 }
  35. username = h.ask("Username, enter for default: ") { |q| q.default = ENV["USER"] }
  36. password = h.ask("Password: ") { |q| q.echo = "*" }
  37.  
  38. begin
  39. Net::SSH.start(hostname, username, :password => password, :port => port) do |ssh|
  40. puts "Uploading your public key... "
  41. ssh.scp.upload! public_key, "my_public_key"
  42.  
  43. puts "Creating '.ssh' directory in your home directory"
  44. ssh.exec!("mkdir .ssh")
  45.  
  46. puts "Concatenating your public key into the authorized_keys file"
  47. ssh.exec!("cat my_public_key >> .ssh/authorized_keys")
  48.  
  49. puts "Removing your public key"
  50. ssh.exec!("rm my_public_key")
  51.  
  52. puts "Setting permissions on .ssh"
  53. ssh.exec!("chmod 700 .ssh")
  54.  
  55. puts "Setting permissions on your authorized_keys file"
  56. ssh.exec!("chmod 600 .ssh/authorized_keys")
  57.  
  58. puts "\nAll done! Enjoy your new, potentially password-free login."
  59. end
  60. rescue Net::SSH::AuthenticationFailed
  61. puts "\nWhat we've got here... is a failure to communicate. There was a problem authenticating you."
  62. end
  63. end
  64. end
Add Comment
Please, Sign In to add comment