Download File via SCP in Ruby

To download a file vie SCP under Ruby, you can just use the NET::SCP class included in ruby like that:

require "net/scp"

=begin
Downloads a single file or a folder via scp
Parameters:
- +host::         +string+  remote IP or domain to get the file / folder from
- +ort+::         +string+  remote port
- +use+r::        +string+  remote user
- +remoteFile+::  +string+  absolute path to file / folder on remote host
- +localFile+::   +string+  absolute path to file / folder on local machine
- +sshKey+::      +string+  SSH key to use for authentication
- +recursive+::   +boolean+ whether to download a path recursively or not (defaults to false)
=end
def downloadFileOverSCP(host, port, user, remoteFile, localFile, sshKey, recursive = false)

  options = {
      :ssh => {
          :keys => sshKey,
          :port => port
      },
      :recursive => recursive
  }

  Net::SCP.download!(host, user, remoteFile, localFile, options) do |ch, name, received, total|

    percentage = format('%.2f', received.to_f / total.to_f * 100) + '%'

    print "Saving to #{name}: Received #{received} of #{total} bytes" + " (#{percentage})                                                                                   \r"

    STDOUT.flush
  end
  puts "Download completed!"
end

downloadFileOverSCP(
    'ask-sheldon.com',
    22,
    'mastermind',
    '/var/www/share/docRoot/current/sql/db_dump_magento_v4_manual.sql.gz',
    'db_dump_magento_v4_manual.sql.gz',
    '/home/sheldon/.ssh/mykeys/id_rsa_super_secret_private_key'

)

For further information about NET::SCP have a look at https://github.com/net-ssh/net-scp.

Leave a Reply

Your email address will not be published. Required fields are marked *

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.