Script for posting SSH keys to a remote host


/ Published in: Ruby
Save to your folder(s)



Copy this code and paste it in your HTML
  1. #!/usr/bin/env ruby
  2. require 'rubygems'
  3. require 'net/ssh'
  4.  
  5. $keyfile = "/Users/nate/.ssh/mypubkey.pub"
  6. $connect_host = "somehost.com"
  7.  
  8. # Determines whether an ~/.ssh directory exists on the client side
  9. def remote_ssh_directory_exists?(connection)
  10. output = ""
  11. cmd_check_ssh = "test -e ~/.ssh && echo 1"
  12. connection.exec!(cmd_check_ssh) do |ch, stream, data|
  13. output << data if stream == :stdout
  14. end
  15. output.chomp == "1"
  16. end
  17.  
  18. def remote_authorized_key_file_exists?(connection)
  19. output = ""
  20. cmd_check_keyfile = "test -e ~/.ssh/authorized_keys && echo 1"
  21. connection.exec!(cmd_check_keyfile) do |ch, stream, data|
  22. output << data if stream == :stdout
  23. end
  24. output.chomp == "1"
  25. end
  26.  
  27. # Creats an authorized key file (.ssh/authorized_keys) on the remote host
  28. def create_authorized_keys_file(connection, stdout)
  29. connection.exec!("touch ~/.ssh/authorized_keys")
  30. stdout << "- Created ~/.ssh/authorized_keys\n"
  31. end
  32.  
  33. begin
  34. print "Enter username to connect at host (e.g 'nate'@somehost.com) ->"
  35. uname = gets.chomp
  36. print "Remote password ->"
  37. pwd = gets.chomp
  38. local_key = open($keyfile) { |f| f.read }
  39. stdout = ""
  40.  
  41. Net::SSH.start($connect_host, uname, :password => pwd) do |ssh|
  42. if remote_ssh_directory_exists?(ssh)
  43. stdout << "- Dependency: SSH folder exists [yes]\n"
  44. # check if the authorized_keys file exists
  45. if remote_authorized_key_file_exists?(ssh)
  46. stdout << "- Dependency: authorized_keys exists [yes]\n"
  47. else
  48. stdout << "- Dependency: authorized_keys exists [no]\n"
  49. create_authorized_keys_file(ssh, stdout)
  50. end
  51. else
  52. stdout << "- Dependency: SSH folder exists [no]\n"
  53. ssh.exec!("mkdir ~/.ssh")
  54. stdout << "- Created .ssh folder\n"
  55. create_authorized_keys_file(ssh, stdout)
  56. end
  57.  
  58. ssh.exec!("echo \"#{local_key}\" >> ~/.ssh/authorized_keys")
  59. stdout << "- Added key to file [yes]"
  60. end
  61. puts stdout
  62. end

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.