用于将SSH密钥发布到远程主机的脚本

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用于将SSH密钥发布到远程主机的脚本相关的知识,希望对你有一定的参考价值。

  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 "
  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] "
  44. # check if the authorized_keys file exists
  45. if remote_authorized_key_file_exists?(ssh)
  46. stdout << "- Dependency: authorized_keys exists [yes] "
  47. else
  48. stdout << "- Dependency: authorized_keys exists [no] "
  49. create_authorized_keys_file(ssh, stdout)
  50. end
  51. else
  52. stdout << "- Dependency: SSH folder exists [no] "
  53. ssh.exec!("mkdir ~/.ssh")
  54. stdout << "- Created .ssh folder "
  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

以上是关于用于将SSH密钥发布到远程主机的脚本的主要内容,如果未能解决你的问题,请参考以下文章

利用ssh-copy-id复制公钥到多台服务器

xshell进行ssh链接报错“所选的用户密钥未在远程主机上注册”处理

使用sshpass 和 ssh-copy-id批量拷贝公钥到远程主机

使用 SSH 密钥连接到远程 Centos 服务器

通过 ssh 在远程主机上启动 bash 脚本

记一次使用Xshell登陆提示所选用户密钥未在远程主机上注册