Friday, November 23, 2012

Simple Script to Update All of Your Ubuntu Machines Securely Over SSH from One Central Location

First configure certificate-based authentication with no password on the server that will manage the updates for the rest of your hosts:

$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/<YOURUSERNAME>/.ssh/id_rsa): <ENTER>
Enter passphrase (empty for no passphrase): <ENTER>
Enter same passphrase again: <ENTER>
Your identification has been saved in /home/<YOURUSERNAME>/.ssh/id_rsa.
Your public key has been saved in /home/<YOURUSERNAME>/.ssh/id_rsa.pub.
The key fingerprint is:
82:ef:d2:3a:b3:5f:9d:bc:41:ac:10:42:8f:a3:24:02 <YOURUSERNAME>@<THE_UPDATE_SERVER>
The key's randomart image is:
+--[ RSA 2048]----+
|    E.. .        |
|       o o       |
|      . = o      |
|       + + . .   |
|      o S .   o  |
|     .  .  . = . |
|     ...    o =  |
|    . . +  .   o |
|     .. .=.   .  |
+-----------------+

This will generate ~/.ssh/id_rsa.pub - copy the contents of this file into ~/.ssh/authorized_keys on every host you'd like to update (~/.ssh/authorized_keys should be the home folder of the user that will be used to ssh into the host that will obtain an update).

Once you can ssh into each host from the server without entering a password, create the file /usr/local/etc/update_da_boxen.config on the update server:

$ sudo touch /usr/local/etc/update_da_boxen.config

Next include one username@host_to_update entry on each line within /usr/local/etc/update_da_boxen.config:

johndoe@firsthosttoupdate
jackie@seconfdhosttoupdate
janedee@thirdhosttoupdate

Save your changes and ensure the file is only readable by root:

chmod 600 /usr/local/etc/update_da_boxen.config && chown root:root /usr/local/etc/update_da_boxen.config

Next create /usr/local/scripts/update_da_boxen.rb:

#!/usr/bin/env ruby
target_user_at_hosts_file = '/usr/local/etc/update_da_boxen.config'
File.read(target_user_at_hosts_file).each_line do |l|
  user_at_host = l.strip.chomp
  system("ssh #{user_at_host} 'sudo apt-get update'")
  system("ssh #{user_at_host} 'sudo apt-get upgrade --assume-yes'")
  system("ssh #{user_at_host} 'sudo apt-get dist-upgrade --assume-yes'")
end

Save your changes and make /usr/local/scripts/update_da_boxen.rb executable:

$ sudo chmod 700 /usr/local/scripts/update_da_boxen.rb && sudo chown root:root /usr/local/scripts/update_da_boxen.rb

To ensure the example script above works, your remote SSH user must be added as a sudoer on the client host that will be included in the update pool:

# visudo

If you don't want to have to type a password to obtain sudo authorization, enter the following:

<YOURUSERNAME> ALL=(ALL:ALL) NOPASSWD:ALL

Replace <YOURUSERNAME> with the SSH user of the host that will be updated.

Cheers! 

No comments:

Post a Comment