public
Description: My set of personal Thor scripts.
Homepage:
Clone URL: git://github.com/crnixon/thor_tasks.git
Clinton R. Nixon (author)
Sat Sep 19 08:31:34 -0700 2009
thor_tasks / ssh.thor
100644 28 lines (24 sloc) 1.105 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#!/usr/bin/env ruby
 
class Ssh < Thor
  require 'net/sftp'
  require 'highline/import'
  
  desc "install_key <hostname>", "installs your public key on the remote host."
  method_options :username => :string, :password => :string, :key => :string
  def install_key(host)
    username = options['username'] || ask("Enter your username: ") { |q| q.default = ENV['USER'] }
    password = options['password'] || ask("Enter your password: ") { |q| q.echo = false }
    key = options['key'] || ask("Enter your key file location: ") { |q| q.default = '~/.ssh/id_rsa.pub' }
    key = File.expand_path(key)
    
    Net::SFTP.start(host, username, :password => password) do |sftp|
      sftp.mkdir!('.ssh', :permissions => 0700) rescue true
      current_keys = sftp.download!(".ssh/authorized_keys") rescue ''
      new_key = File.read(key) rescue ''
      
      unless current_keys.index(new_key)
        sftp.file.open(".ssh/authorized_keys", "w", 0600) do |f|
          f.puts current_keys unless current_keys.empty?
          f.puts new_key unless new_key.empty?
        end
      end
    end
  end
end