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 (https://github.com/net-ssh/net-sftp) accomplishes this with ease.

Here is how you can do it too:

#!/usr/bin/env ruby require 'rubygems'require 'optparse'require 'net/sftp' options = {}OptionParser.new 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| sftp.download!(options[:file], options[:file])end puts options[:file]

Example usage:

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

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

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


分享给朋友:
您可能感兴趣的文章:
随机阅读: