Module: SecureShellForever

Defined in:
lib/ssh-forever.rb

Class Method Summary collapse

Class Method Details

.flunk(message) ⇒ Object



54
55
56
57
# File 'lib/ssh-forever.rb', line 54

def flunk(message)
  STDERR.puts message
  exit 1
end

.generate_public_keyObject



41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/ssh-forever.rb', line 41

def generate_public_key
  silence_stream(STDOUT) do
    silence_stream(STDERR) do
      pipe = IO.popen('ssh-keygen -t rsa', 'w')
      6.times do
        pipe.puts "\n"
      end
    end
  end
  Process.wait
  flunk("Oh dear. I was unable to generate your public key. Run the command 'ssh-keygen -t rsa' manually to find out why.") unless $? == 0
end

.keyObject



37
38
39
# File 'lib/ssh-forever.rb', line 37

def key
  `cat #{public_key_path}`.strip
end

.public_key_pathObject



59
60
61
# File 'lib/ssh-forever.rb', line 59

def public_key_path
  File.expand_path('~/.ssh/id_rsa.pub')
end

.remote_commandObject



27
28
29
30
31
32
33
34
35
# File 'lib/ssh-forever.rb', line 27

def remote_command
  commands = []
  commands << 'mkdir -p ~/.ssh'
  commands << 'chmod 700 ~/.ssh'
  commands << 'touch ~/.ssh/authorized_keys'
  commands << 'chmod 700 ~/.ssh/authorized_keys'
  commands << "echo #{key} >> ~/.ssh/authorized_keys"
  commands.join(' && ')
end

.run(login, options = {}) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/ssh-forever.rb', line 3

def run(, options = {})
  unless File.exists?(public_key_path)
    STDERR.puts "You do not appear to have a public key. I expected to find one at #{public_key_path}\n"
    STDERR.print "Would you like me to generate one? [Y/n]"
    result = STDIN.gets.strip
    unless result == '' or result == 'y' or result == 'Y'
      flunk %Q{Fair enough, I'll be off then. You can generate your own by hand using\n\n\tssh-keygen -t rsa}
    end
    generate_public_key
  end
  
  args = [
      ' ',
      ("-p #{options[:port]}" if options[:port] =~ /^\d+$/)
    ].compact.join(' ')
    
  puts "Copying your public key to the remote server. Prepare to enter your password for the last time."
  `ssh #{}#{args} "#{remote_command}"`
  exit 1 unless $?.exitstatus == 0
  
  puts "Success. From now on you can just use plain old 'ssh'. Logging you in..."
  exec "ssh #{}#{args}"
end

.silence_stream(stream) ⇒ Object



63
64
65
66
67
68
69
70
# File 'lib/ssh-forever.rb', line 63

def silence_stream(stream)
  old_stream = stream.dup
  stream.reopen(RUBY_PLATFORM =~ /mswin/ ? 'NUL:' : '/dev/null')
  stream.sync = true
  yield
ensure
  stream.reopen(old_stream)
end