Created
March 21, 2012 18:27
-
-
Save thiagofm/2150801 to your computer and use it in GitHub Desktop.
scriptzor.rb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'net/ssh' | |
module TestingMethods | |
def create_test #uses the current authorized_keys | |
Net::SSH.start(@server, 'root') do |ssh| | |
ssh.exec "cat ~/.ssh/authorized_keys >> #{@ak_path}" | |
end | |
end | |
def remove_test | |
Net::SSH.start(@server, 'root') do |ssh| | |
ssh.exec "rm #{@ak_path}" | |
end | |
end | |
def print_keys | |
Net::SSH.start(@server, 'root') do |ssh| | |
ssh.exec "cat #{@ak_path}" | |
end | |
end | |
end | |
class AuthorizedKeys | |
include TestingMethods | |
def initialize(server,ak_path) | |
@server = server | |
@ak_path = ak_path | |
end | |
# Add key to ak_path | |
def add_key(key) | |
# Checks if key already exists | |
if !self.key_exists?(key) | |
Net::SSH.start(@server, 'root') do |ssh| | |
# Appends to the EOF | |
ssh.exec "echo \"\n#{key}\" >> #{@ak_path}" | |
end | |
puts "Success: Added key for server #{@server} in file #{@ak_path}." | |
else | |
puts "Error: Key already exists." | |
end | |
end | |
# Checks if key exist in ak_path | |
def key_exists?(key) | |
Net::SSH.start(@server, 'root') do |ssh| | |
stdout = "" | |
ssh.exec!("cat #{@ak_path}") do |channel, stream, data| | |
stdout << data if stream == :stdout | |
end | |
stdout # Output of file | |
# Checks each line if its the key | |
file_lines = stdout.split /\n/ # Splits the file into lines | |
counter = 0 | |
file_lines.each do |line| | |
if(line == key) | |
return true | |
end | |
end | |
return false | |
end | |
end | |
end | |
AK_PATH = '~/.ssh/authorized_keys' | |
SERVER_LIST = [ | |
's1', | |
's2' | |
] | |
KEYS = [ | |
'gingateste teste', | |
'gingakey teste2', | |
'gingakeys teste3' | |
] | |
SERVER_LIST.each do |server| | |
puts "### Starting script for #{server} ###\n" | |
ak = AuthorizedKeys.new(server,AK_PATH) | |
#puts "### Creating test ###\n" | |
#ak.create_test #testing method | |
#puts "### Adding keys ###\n" | |
puts "### Adding keys ###\n" | |
KEYS.each do |key| | |
ak.add_key key | |
#ak.add_key key # test to make sure no duplicated keys are added | |
end | |
#puts "### Checking if added keys exist ###\n" | |
#KEYS.each do |key| | |
# puts "#{key}: #{ak.key_exists?(key)}" | |
#end | |
#puts "### Done with testing ###\n" | |
puts "### Done for #{server} ###\n" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment