Ruby SFTP download script


Some applications have need to download data from remote SFTP server. PHP offers limited choices here. Options boil down to installing ssh2 extension or including phpseclib library to your project, both of which come with too much overhead for something straightforward as SFTP file download.

On the other hand Ruby, which is paired with net-sftp gem ( accomplishes this with ease.

Here is how you can do it too:

#!/usr/bin/env ruby require 'rubygems'require 'optparse'require 'net/sftp' options = {} do |opts| opts.banner = "Sftp download script by StuntCoders" opts.on('-h', '--host HOST', 'Sftp host') do |host| options[:host] = host end opts.on('-u', '--username USERNAME', 'Sftp username') do |username| options[:username] = username end opts.on('-p', '--password PASSWORD', 'Sftp password') do |password| options[:password] = password end opts.on('-f', '--file FILE', 'File to download') do |file| options[:file] = file endend.parse! raise 'Host parameter must be provided' if options[:host].nil?raise 'Username parameter must be provided' if options[:username].nil? Net::SFTP.start(options[:host], options[:username], password: options[:password]) do |sftp|!(options[:file], options[:file])end puts options[:file]

Example usage:

ruby sc-sftp-download -h -u username -p password -f file.txt

After completing download script outputs file name to standard output allowing piping:

ruby sc-sftp-download -h -u username -p password -f file.txt | xargs less