Skip to content

Instantly share code, notes, and snippets.

@mindware
Last active August 29, 2015 14:15
Show Gist options
  • Save mindware/a1b2017bebc688263a0e to your computer and use it in GitHub Desktop.
Save mindware/a1b2017bebc688263a0e to your computer and use it in GitHub Desktop.
Ruby script to generate 4096 ssh key and display ansible commands to distribute the public key to all machines
### Ask for SENSITIVE DATA:
puts "\nLet's help you generate the RSA keys and distribute it to your machines.\n\n"
print "Enter a secret passphrase to use for the key (save it well!): "
passphrase = gets.strip
print "Enter how many iterations (500 for security + performance, 1000 > for maximum security):"
iterations = gets.strip
print "Enter the name of the remote user: "
remote_user= gets.strip
print "Enter a comment to identify this key in the authorized_host (ie: [email protected]): "
comment= gets.strip
# Key variables:
print "Enter the file name for the private key (ie: id_rsa): "
private_key = gets.strip
path_to_key = File.expand_path("~/.ssh/#{private_key}.pub")
path_to_private_key = File.expand_path("~/.ssh/#{private_key}")
# Lets generate our Keys:
if(File.exist?(path_to_private_key) or File.exists?(path_to_key))
puts "The keys for '#{private_key}' already exist. "+
"Back them up and remove them, if you want to run this script."
exit
end
puts "Now generating the private key: #{private_key} (this will take a little while)..."
command = "ssh-keygen -b 4096 -N #{passphrase} -f #{path_to_private_key} -o -a #{iterations} -C #{comment}"
puts "Running: #{command}"
result = `#{command}`
puts "Result: #{result}"
command = "chmod 0600 #{path_to_key}"
puts "Changing permissions: #{command}"
result = `#{command}`
puts "Result: #{result}"
command = "chmod 0600 #{path_to_private_key}"
puts "Changing permissions: #{command}"
result = `#{command}`
puts "Result: #{result}"
puts "Done.\n"
puts "\nNow copy paste this:\n"+
"ssh-agent bash\n"+
"ssh-add #{path_to_private_key}\n\n"+
"Then enter the passphrase:\n#{passphrase}\n\n"+
"Finally, after that you can run:\n"+
"ansible -i hosts -m authorized_key -a "+
"\"key='{{ lookup('file', '#{path_to_key}') }}' user=#{remote_user}\" "+
"-u #{remote_user} all -k\n"
# Output will be something similar to this:
# ansible -i hosts -m authorized_key -a
# "key='{{ lookup('file', '/home/vagrant/.ssh/id_rsa.pub') }}' user=vagrant"
# -u vagrant all -k
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment