first commit
[past_intern.git] / hw-intern-09 / scripts / ssh-keys / initialize.rb
blobf94577cc7b1423592cb9aaef232bfc91bb6715d9
1 #!/usr/bin/ruby -w
2 # This script helps create an automatic login with SSH
3 # without a password. By creating a rsa key pair.
4 # By Chris Choi
5 require 'rubygems'
6 require 'net/ssh'
7 require 'net/scp'
9 pinged_machines = "./pinged_machines"
11 # Check SSH connection first on the remote machines!!
12 if system("bash ./test_connection.sh") then
13 # The program nmap displays a lot of rubbish 
15         # Program interface
16         puts "This script helps create an automatic login with SSH"
17         puts "so that you don't have to SSH with a password in the future"
18         puts "First I need your login for the machines you wish to gain access to:"
19         puts "Login:"
20         user = gets.chomp
21         puts "Password:"
22         pass = gets.chomp
23         status = 0
25         # Login to the remote machines and create the ~/.ssh folder
26         # and upload the rsa key pair into the folder.
27         fp = File.open(pinged_machines)
28         fp.each do |machine|
29                 if machine.include?("#") then
30                         puts "Skipping #{machine}"      
31                 else
32                         # Creating ~/.ssh folder on the remote machines
33                         puts "Creating .ssh folder on #{machine}"
34                         Net::SSH.start( machine.chomp, user, :password => pass ) do |session|
35                                 error = session.exec!("mkdir -p ~/.ssh")
36                                 status = session.exec!("echo $?")
37                                 status = status.chomp
38                         end
39                 end
40         end
41         fp.close
43         if status.chomp == '0' then 
44                 # Create the rsa key pair
45                 system('ssh-keygen -t rsa')
46                 puts ""
47                 puts ""
48                 system('bash upload_rsa.sh')
49                 puts "Done! Now SSH into the machines and try if you can login without entering"
50                 puts "a password! By doing: ssh some_user_name@some_host"
52         else
53                 puts "Opps! There seems to be some problems with #{machine}"
54                 puts "Error: #{error}"
55         end
57         # Warning Note!
58         puts ""
59         puts "IMPORTANT NOTE!!:"
60         puts "If this small script does not work, depending on your version of SSH" 
61         puts "you might have to do the following"
62         puts "- Put the public key in '.ssh/auhtorized_keys2'"
63         puts "- Change the permission of .ssh to 700"
64         puts "- Change the permission of .ssh/authorized_keys2 to 640"
65 end