class Net::SCP

++
of zero.
It will be terminated when the remote process closes with an exit status
pipe (via Net::SSH::Connection::Channel#eof!) and leaves the pipe to drain.
Tells the server that no more data is forthcoming from this end of the
== Net::SCP#finish_state
Net::SCP::Upload#upload_current_state.
Otherwise, set the current upload source and go to
to Net::SCP::Upload#next_item_state.
‘E’ directive and wait for the server to respond with a 0-byte. Then go
If there is nothing left to upload from the current directory, send an
jump to Net::SCP#finish_state.
If there is nothing left to upload, and there is no parent directory,
== Net::SCP::Upload#next_item_state
0-byte of its own. Then we jump back to Net::SCP::Upload#next_item_state.
send a 0-byte to the server, and wait for the server to respond with a
remains in this state until all data has been sent, at which point we
Reads and sends the next chunk of data to the server. The state machine
== Net::SCP::Upload#send_data_state
server to respond with a 0-byte. Then jump to Net::SCP::Upload#next_item_state.
If current item is a directory, send a ‘D’ directive, and wait for the
then a jump to Net::SCP::Upload#send_data_state.
and then a ‘C’ directive, and then a wait for the server to respond, and
’T’ directive (if :preserve is true), then a wait for the server to respond,
If the current item is a file, send a file. Sending a file starts with a
== Net::SCP::Upload#upload_current_state
Net::SCP::Download#read_directive state to see what we get to download next.
file and we switch to Net::SCP#finish_state. Otherwise we jump back to the
received. If there is no parent directory, then we’re downloading a single
We sent a 0-byte to the server to indicate that the file was successfully
== Net::SCP::Download#finish_read_state
switch to the Net::SCP::Download#finish_read_state.
data has been read, we wait for the server to send a 0-byte, and then we
Bytes are read to satisfy the size of the incoming file. When all pending
== Net::SCP::Download#read_data_state
before moving to the next state.
Regardless of what the next state is, we send a 0-byte to the server
there is no parent directory, we switch over to Net::SCP#finish_state.
Net::SCP::Download#read_data_state. If an ‘E’ directive is received, and
If a ‘C’ directive is received, we switch over to
this error will be reported if the SCP results in an error.
* 2 – error directive. Indicates an error from the other end. Text from
this warning will be reported if the SCP results in an error.
* 1 – warning directive. Indicates a warning from the other end. Text from
* 0 – indicates a successful response from the other end.
directory.
files and directories should be received by the parent of the current
* E – terminator directive. Indicates the end of a directory, and subsequent
will be sent, raw.
permissions/size/name. Immediately following this line, size bytes
* C%o %d %s – a file is being sent next. The file will have the given
directive.
directories will be children of this directory, until a matching ‘E’
a directory with the same name and permissions. Subsequent files and
with the given permissions/size/name, and the recipient should create
* D%o %d %s – a directory change. The process is changing to a directory
downloaded must have mtime/usec/atime/usec attributes preserved.
* T%d %d %d %d – a “times” packet. Indicates that the next file to be
recognized:
Reads a directive line from the input. The following directives are
== Net::SCP::Download#read_directive_state
server, and then switches to Net::SCP::Upload#upload_current_state.
Sets up the initial upload scaffolding and waits for a 0-byte from the
== Net::SCP::Upload#upload_start_state
server. The next state is Net::SCP::Download#read_directive_state.
This is the start state for downloads. It simply sends a 0-byte to the
== Net::SCP::Download#download_start_state
Otherwise, look for upload_start_state.
Then the fun begins. If you’re doing a download, enter the download_start_state.
as the sole non-switch argument to scp.
After those flags, the name of the remote file/directory should be passed
error to upload or download a directory.
* “-r” – recursive transfers should be allowed. Without this, it is an
be sent to indicate the modification and access times of each file.
* “-p” – preserve timestamps. ‘T’ directives (see below) should be/will
it is doing via stderr.
* “-v” – verbose mode; the remote scp process should chatter about what
accordingly.
e.g., that data will be downloaded and it should initialize itself
* “-f” – tells the remote scp process that data should come “from” it,
accordingly.
e.g., that data will be uploaded and it should initialize itself
* “-t” – tells the remote scp process that data will be sent “to” it,
the following parameters, which must be set correctly to avoid errors:
The first step is to invoke the “scp” command on the server. It accepts
contain errors. You have been warned!
reversed engineered from the OpenSSH SCP implementation, and so may
of the SCP protocol won’t be left high-and-dry like I was. The following is
library, I’m documenting it here so that anyone else looking for documentation
Although this information has zero relevance to consumers of the Net::SCP
= Protocol Description

so far for the file, and the size of the file.
remote for uploads), the number of bytes that have been sent or received
will be invoked, indicating the name of the file (local for downloads,
Whenever a new chunk of data is recieved for or sent to a file, the callback
end
puts “#{name}: #{sent}/#{total}”
scp.upload!(“/path/to/local”, “/path/to/remote”) do |ch, name, sent, total|
to #upload or #download (or one of their variants):
To receive progress reports for the current operation, just pass a block
to the user the progress of the current operation.
(and especially in interactive environments) it is desirable to report
outward indication of their progress. For long running uploads or downloads
By default, uploading and downloading proceed silently, without any
== Progress Reporting
end
ssh.scp.download! “/remote/path”, “/local/path”
Net::SSH.start(“remote.host”, “username”, :password => “passwd”) do |ssh|
require ‘net/scp’
require ‘net/ssh’
session:
allowing you to easily grab a Net::SCP reference from an existing Net::SSH
Lastly, Net::SCP adds a method to the Net::SSH::Connection::Session class,
puts open(“scp://user@remote.host/path/to/file”).read
require ‘uri/open-scp’
# if you want to read from a URL voa SCP:
url = URI.parse(“scp://user@remote.host/path/to/file”)
require ‘uri/scp’
# if you just want to parse SCP URL’s:
method to open and read a remote file:
Net::SCP also provides an open-uri tie-in, so you can use the Kernel#open
end
channel.wait
channel = scp.upload(“/local/path”, “/remote/path”)
# event loop to run
# asynchronous upload; call returns immediately and requires SSH
scp.upload! “/local/path”, “/remote/path”
# synchronous (blocking) upload; call blocks until upload completes
Net::SCP.start(“remote.host”, “username”, :password => “passwd”) do |scp|
require ‘net/scp’
Basic usage:
connection, as well as for synchronous, serial copies.
multiple simultaneous SCP copies working in parallel over the same
entire directory trees to and from remote servers. It provides support for
programs to securely and programmatically transfer individual files or
Net::SCP implements the SCP (Secure CoPy) client protocol, allowing Ruby

def self.download!(host, username, remote, local=nil, options={}, &progress)

progress (see "Progress Reporting", under Net::SCP).
to the #download! method. If a block is given, it will be used to report
options (e.g., to set the password, etc.). All other options are passed
:ssh key, the value for that will be passed to the SSH connection as
download from +remote+ to +local+. If the +options+ hash includes an
instantiates a new SCP session on top of it, and then begins a
Starts up a new SSH connection using the +host+ and +username+ parameters,
def self.download!(host, username, remote, local=nil, options={}, &progress)
  options = options.dup
  start(host, username, options.delete(:ssh) || {}) do |scp|
    return scp.download!(remote, local, options, &progress)
  end
end

def self.start(host, username, options={})

block is given, the SCP session is returned.
SSH session is closed automatically when the block terminates. If no
top of it. If a block is given, the SCP session is yielded, and the
Starts up a new SSH connection and instantiates a new SCP session on
def self.start(host, username, options={})
  session = Net::SSH.start(host, username, options)
  scp = new(session)
  if block_given?
    begin
      yield scp
      session.loop
    ensure
      session.close
    end
  else
    return scp
  end
end

def self.upload!(host, username, local, remote, options={}, &progress)

progress (see "Progress Reporting", under Net::SCP).
to the #upload! method. If a block is given, it will be used to report
options (e.g., to set the password, etc.). All other options are passed
:ssh key, the value for that will be passed to the SSH connection as
upload from +local+ to +remote+. If the +options+ hash includes an
instantiates a new SCP session on top of it, and then begins an
Starts up a new SSH connection using the +host+ and +username+ parameters,
def self.upload!(host, username, local, remote, options={}, &progress)
  options = options.dup
  start(host, username, options.delete(:ssh) || {}) do |scp|
    scp.upload!(local, remote, options, &progress)
  end
end

def await_response(channel, next_state)

at +next_state+ and continue processing.
#await_response_state), at which point the state machine will pick up
things just pause until the server replies with a 0 (see
Causes the state machine to enter the "await response" state, where
def await_response(channel, next_state)
  channel[:state] = :await_response
  channel[:next ] = next_state.to_sym
  # check right away, to see if the response is immediately available
  await_response_state(channel)
end

def await_response_state(channel)

exception is raised.
next state (see +await_response+). If the response is not a 0, an
an integer 0 as the only byte, the state machine is kicked into the
machine will remain in this state. As soon as the server replies with
response" state. As long as there is no data ready to process, the
The action invoked while the state machine remains in the "await
def await_response_state(channel)
  return if channel[:buffer].available == 0
  c = channel[:buffer].read_byte
  raise Net::SCP::Error, "#{c.chr}#{channel[:buffer].read}" if c != 0
  channel[:next], channel[:state] = nil, channel[:next]
  send("#{channel[:state]}_state", channel)
end

def download(remote, local, options={}, &progress)

channel.wait
channel = scp.download("/remote/path", "/local/path")

the Net::SSH event loop until the channel's #active? method returns false.
you can either call the #wait method on the channel, or otherwise run
object that will support the download. To wait for the download to finish,
This method will return immediately, returning the Net::SSH::Connection::Channel

end (useful for debugging).
* :verbose - the process should result in verbose output on the server
* :preserve - the atime and mtime of the file should be preserved.
machine.
should be downloaded to a new directory named +local+ on the local
* :recursive - the +remote+ parameter refers to a remote directory, which

The following options are recognized:
Inititiate a synchronous (non-blocking) download from +remote+ to +local+.
def download(remote, local, options={}, &progress)
  start_command(:download, local, remote, options, &progress)
end

def download!(remote, local=nil, options={}, &progress)

data = download!("/remote/path")

and the resulting string returned.
only a single file), the file will be downloaded to an in-memory buffer
If +local+ is nil, and the download is not recursive (e.g., it is downloading

scp.download!("/remote/path", "/local/path")

object that is returned.
calling #download and then calling the #wait method on the channel
Same as #download, but blocks until the download finishes. Identical to
def download!(remote, local=nil, options={}, &progress)
  destination = local ? local : StringIO.new.tap { |io| io.set_encoding('BINARY') }
  download(remote, destination, options, &progress).wait
  local ? true : destination.string
end

def finish_state(channel)

of the pipe, and allows the pipe to drain until the server closes it.
It just tells the server not to expect any more data from this end
The action invoked when the state machine is in the "finish" state.
def finish_state(channel)
  channel.eof!
end

def initialize(session)

object.
Creates a new Net::SCP session on top of the given Net::SSH +session+
def initialize(session)
  @session = session
  self.logger = session.logger
end

def progress_callback(channel, name, sent, total)

set, this does nothing.
Invoked to report progress back to the client. If a callback was not
def progress_callback(channel, name, sent, total)
  channel[:callback].call(channel, name, sent, total) if channel[:callback]
end

def scp_command(mode, options)

string, ready to execute.
(:verbose, :recursive, :preserve). Returns the command-line as a
for the given +mode+ (:upload or :download) and with the given options
Constructs the scp command line needed to initiate and SCP session
def scp_command(mode, options)
  command = "scp "
  command << (mode == :upload ? "-t" : "-f")
  command << " -v" if options[:verbose]
  command << " -r" if options[:recursive]
  command << " -p" if options[:preserve]
  command
end

def shellescape(path)

Imported from ruby 1.9.2 shellwords.rb
def shellescape(path)
  # Convert path to a string if it isn't already one.
  str = path.to_s
  # ruby 1.8.7+ implements String#shellescape
  return str.shellescape if str.respond_to? :shellescape
  # An empty argument will be skipped, so return empty quotes.
  return "''" if str.empty?
  str = str.dup
  # Process as a single byte sequence because not all shell
  # implementations are multibyte aware.
  str.gsub!(/([^A-Za-z0-9_\-.,:\/@\n])/n, "\\\\\\1")
  # A LF cannot be escaped with a backslash because a backslash + LF
  # combo is regarded as line continuation and simply ignored.
  str.gsub!(/\n/, "'\n'")
  return str
end

def start_command(mode, local, remote, options={}, &callback)

(See Net::SCP::Upload and Net::SCP::Download).
sets up a state machine to use to process the upload or download.
it (see #scp_command). It then sets up the necessary callbacks, and
Opens a new SSH channel and executes the necessary SCP command over
def start_command(mode, local, remote, options={}, &callback)
  session.open_channel do |channel|
    if options[:shell]
      escaped_file = shellescape(remote).gsub(/'/) { |m| "'\\''" }
      command = "#{options[:shell]} -c '#{scp_command(mode, options)} #{escaped_file}'"
    else
      command = "#{scp_command(mode, options)} #{shellescape remote}"
    end
    channel.exec(command) do |ch, success|
      if success
        channel[:local   ] = local
        channel[:remote  ] = remote
        channel[:options ] = options.dup
        channel[:callback] = callback
        channel[:buffer  ] = Net::SSH::Buffer.new
        channel[:state   ] = "#{mode}_start"
        channel[:stack   ] = []
        channel[:error_string] = ''
        channel.on_close                  { |ch2| send("#{channel[:state]}_state", channel); raise Net::SCP::Error, "SCP did not finish successfully (#{channel[:exit]}): #{channel[:error_string]}" if channel[:exit] != 0 }
        channel.on_data                   { |ch2, data| channel[:buffer].append(data) }
        channel.on_extended_data          { |ch2, type, data| debug { data.chomp } }
        channel.on_request("exit-status") { |ch2, data| channel[:exit] = data.read_long }
        channel.on_process                { send("#{channel[:state]}_state", channel) }
      else
        channel.close
        raise Net::SCP::Error, "could not exec scp on the remote host"
      end
    end
  end
end

def upload(local, remote, options={}, &progress)

channel.wait
channel = scp.upload("/local/path", "/remote/path")

the Net::SSH event loop until the channel's #active? method returns false.
you can either call the #wait method on the channel, or otherwise run
object that will support the upload. To wait for the upload to finish,
This method will return immediately, returning the Net::SSH::Connection::Channel

of decreasing interactivity.
to 2048. Changing this value may improve throughput at the expense
* :chunk_size - the size of each "chunk" that should be sent. Defaults
end (useful for debugging).
* :verbose - the process should result in verbose output on the server
* :preserve - the atime and mtime of the file should be preserved.
server.
should be uploaded to a new directory named +remote+ on the remote
* :recursive - the +local+ parameter refers to a local directory, which

The following options are recognized:
Inititiate a synchronous (non-blocking) upload from +local+ to +remote+.
def upload(local, remote, options={}, &progress)
  start_command(:upload, local, remote, options, &progress)
end

def upload!(local, remote, options={}, &progress)

that is returned. The return value is not defined.
calling #upload and then calling the #wait method on the channel object
Same as #upload, but blocks until the upload finishes. Identical to
def upload!(local, remote, options={}, &progress)
  upload(local, remote, options, &progress).wait
end