1. Computing

Net:SSH--Transferring Files with Net::SCP

By

4 of 6

Progress Bars and Feedback

When you're transferring a large file, it's good to have some kind of indication of the progress being made. Otherwise, you may think it's stalled and have no way of knowing. While transferring files, the SSH server on the remote host will give you constant feedback of which file is being transferred, its size and how many bytes have been transferred.

As with methods like exec, the upload and download methods accept a block. This block takes four arguments: the channel, the filename, bytes sent, and total bytes in file. You can use this to implement a crude progress bar, or to generate signals for a GUI system to update a progress bar.

#!/usr/bin/env ruby
require 'rubygems'
require 'net/ssh'
require 'net/scp'

hostname = '192.168.1.113'
username = 'user
password = 'pass

Net::SSH.start( hostname, username, :password => password ) do|ssh|
  ssh.scp.upload!( 'large.zip', '.' ) do|ch, name, sent, total|
    print "\r#{name}: #{(sent.to_f * 100 / total.to_f).to_i}%"
  end
  
end
  1. About.com
  2. Computing
  3. Ruby
  4. Networking
  5. SSH
  6. Transferring Files with Net::SCP---Progress Bars and Feedback

©2014 About.com. All rights reserved.