Skip to content

Instantly share code, notes, and snippets.

@Karunamon
Created April 14, 2014 15:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Karunamon/10656663 to your computer and use it in GitHub Desktop.
Save Karunamon/10656663 to your computer and use it in GitHub Desktop.
SSH Key Distribution
#!/usr/bin/env ruby
# distribute_ssh_keys.rb
# Jason Boxman <jasonb@edseek.com>
# 20110624
# From http://blog.edseek.com/archives/2011/06/27/ssh-key-distribution-with-ruby-and-netsshm/
# Unsure of the license on this. Tread carefully.
#
# Sanely deploy ssh public key to multiple hosts.
# Will prompt for ssh password using highline.
#
require 'optparse'
require 'fcntl'
require 'rubygems'
require 'net/ssh'
require 'net/ssh/multi'
require 'net/ssh/askpass'
require 'highline/import'
OptionParser.new do |o|
o.on('-f', '--keyfile FILENAME',
'You must specify a public key to distribute') do |filename|
$keyfile = filename
$keydata = IO.read($keyfile).gsub(/\n/, '') if File.exists?($keyfile)
raise 'No keydata' if $keydata.nil?
end
o.on('-h') {puts o; exit}
o.parse!
end
# Based upon this thread or $stdin gets messed up:
# http://stackoverflow.com/questions/1992323/reading-stdin-multiple-times-in-bash
old = $stdin.dup
new = File::open('/dev/tty')
$stdin.reopen(new)
passwd = ask("Password?") {|q| q.echo = false}
$stdin.reopen(old)
new.close
options = {
:concurrent_connections => 5,
:on_error => :ignore,
:default_user => 'root'
}
sess_options = {
:password => passwd,
:auth_methods => ['password'],
:verbose => :warn
}
def get_hosts
(STDIN.fcntl(Fcntl::F_GETFL, 0) == 0) ? ARGF.collect {|f| f} : nil
end
# Iterate over a group of servers and deploy an SSH key
Net::SSH::Multi.start(options) do |session|
session.use(sess_options) { get_hosts }
session.exec <<-EOT
test -e ~/.ssh || mkdir ~/.ssh
test -e ~/.ssh/authorized_keys || touch ~/.ssh/authorized_keys
if ! grep -q "#{$keydata}" ~/.ssh/authorized_keys ; then
chmod go-w ~ ~/.ssh ~/.ssh/authorized_keys ; \
echo "#{$keydata}" >> ~/.ssh/authorized_keys
fi
EOT
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment