Created
March 28, 2010 06:43
-
-
Save kmdsbng/346612 to your computer and use it in GitHub Desktop.
This file contains 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 'tempfile' | |
def main | |
user = ARGV[0] | |
remote = ARGV[1] | |
if user_existed?(user) | |
STDERR.puts "already exist user #{user}. do nothing." | |
exit 1 | |
end | |
pub_key = retrieve_pub_key(user, remote) | |
if pub_key.to_s.chomp.empty? | |
STDERR.puts "could not retrieve #{user}'s authorized_keys on #{remote}." | |
exit 1 | |
end | |
create_user_and_set_pub_key(user, pub_key) | |
end | |
def retrieve_pub_key(user, remote) | |
pub_key = %x(ssh #{remote} sudo cat ~#{user}/.ssh/authorized_keys) | |
$? == 0 ? pub_key : nil | |
end | |
def user_existed?(user) | |
%x(id #{user}) | |
$? == 0 | |
end | |
def create_user_and_set_pub_key(user, pub_key) | |
path = create_pub_key_temp_file(pub_key) | |
%x(sudo /usr/sbin/useradd #{user}) | |
%x(sudo mkdir ~#{user}/.ssh) | |
%x(sudo chmod 700 ~#{user}/.ssh) | |
%x(sudo cp #{path} ~#{user}/.ssh/authorized_keys) | |
%x(sudo chmod 600 ~#{user}/.ssh/authorized_keys) | |
%x(sudo chown -R #{user}:mmj ~#{user}/.ssh) | |
end | |
def create_pub_key_temp_file(pub_key) | |
tempfile = Tempfile.new('pubkey') | |
tempfile.write pub_key | |
tempfile.close | |
tempfile.path | |
end | |
if $0 == __FILE__ | |
main | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment