用于将SSH密钥发布到远程主机的脚本
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用于将SSH密钥发布到远程主机的脚本相关的知识,希望对你有一定的参考价值。
#!/usr/bin/env ruby require 'rubygems' require 'net/ssh' $keyfile = "/Users/nate/.ssh/mypubkey.pub" $connect_host = "somehost.com" # Determines whether an ~/.ssh directory exists on the client side def remote_ssh_directory_exists?(connection) output = "" cmd_check_ssh = "test -e ~/.ssh && echo 1" connection.exec!(cmd_check_ssh) do |ch, stream, data| output << data if stream == :stdout end output.chomp == "1" end def remote_authorized_key_file_exists?(connection) output = "" cmd_check_keyfile = "test -e ~/.ssh/authorized_keys && echo 1" connection.exec!(cmd_check_keyfile) do |ch, stream, data| output << data if stream == :stdout end output.chomp == "1" end # Creats an authorized key file (.ssh/authorized_keys) on the remote host def create_authorized_keys_file(connection, stdout) connection.exec!("touch ~/.ssh/authorized_keys") stdout << "- Created ~/.ssh/authorized_keys " end begin print "Enter username to connect at host (e.g 'nate'@somehost.com) ->" uname = gets.chomp print "Remote password ->" pwd = gets.chomp local_key = open($keyfile) { |f| f.read } stdout = "" Net::SSH.start($connect_host, uname, :password => pwd) do |ssh| if remote_ssh_directory_exists?(ssh) stdout << "- Dependency: SSH folder exists [yes] " # check if the authorized_keys file exists if remote_authorized_key_file_exists?(ssh) stdout << "- Dependency: authorized_keys exists [yes] " else stdout << "- Dependency: authorized_keys exists [no] " create_authorized_keys_file(ssh, stdout) end else stdout << "- Dependency: SSH folder exists [no] " ssh.exec!("mkdir ~/.ssh") stdout << "- Created .ssh folder " create_authorized_keys_file(ssh, stdout) end ssh.exec!("echo "#{local_key}" >> ~/.ssh/authorized_keys") stdout << "- Added key to file [yes]" end puts stdout end
以上是关于用于将SSH密钥发布到远程主机的脚本的主要内容,如果未能解决你的问题,请参考以下文章
xshell进行ssh链接报错“所选的用户密钥未在远程主机上注册”处理