/ Published in: Ruby
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
#!/usr/bin/env ruby require 'rubygems' require 'net/ssh' $keyfile = "/Users/nate/.ssh/mypubkey.pub" $connect_host = "somehost.com" # Determines whether an ~/.ssh directory exists on the client side def remote_ssh_directory_exists?(connection) output = "" cmd_check_ssh = "test -e ~/.ssh && echo 1" connection.exec!(cmd_check_ssh) do |ch, stream, data| output << data if stream == :stdout end output.chomp == "1" end def remote_authorized_key_file_exists?(connection) output = "" cmd_check_keyfile = "test -e ~/.ssh/authorized_keys && echo 1" connection.exec!(cmd_check_keyfile) do |ch, stream, data| output << data if stream == :stdout end output.chomp == "1" end # Creats an authorized key file (.ssh/authorized_keys) on the remote host def create_authorized_keys_file(connection, stdout) connection.exec!("touch ~/.ssh/authorized_keys") stdout << "- Created ~/.ssh/authorized_keys\n" end begin print "Enter username to connect at host (e.g 'nate'@somehost.com) ->" uname = gets.chomp print "Remote password ->" pwd = gets.chomp local_key = open($keyfile) { |f| f.read } stdout = "" Net::SSH.start($connect_host, uname, :password => pwd) do |ssh| if remote_ssh_directory_exists?(ssh) stdout << "- Dependency: SSH folder exists [yes]\n" # check if the authorized_keys file exists if remote_authorized_key_file_exists?(ssh) stdout << "- Dependency: authorized_keys exists [yes]\n" else stdout << "- Dependency: authorized_keys exists [no]\n" create_authorized_keys_file(ssh, stdout) end else stdout << "- Dependency: SSH folder exists [no]\n" ssh.exec!("mkdir ~/.ssh") stdout << "- Created .ssh folder\n" create_authorized_keys_file(ssh, stdout) end ssh.exec!("echo \"#{local_key}\" >> ~/.ssh/authorized_keys") stdout << "- Added key to file [yes]" end puts stdout end