Berlin Berlin - 2 months ago 17
Ruby Question

How do I transfer multiple files using Ruby Net::SSH.start?

I want to copy all files from remote host

/root/files/*.log
to my current directory -
./files1/


require 'rubygems'
require 'net/ssh'
require 'net/scp'

Net::SSH.start( scp_hostname, scp_username, :keys => scp_keys, :timeout => 360 ) do |ssh|
ssh.scp.download!( '/root/files/*.log', './files1/' )
ssh.exec!( .. )
ssh.exec!( .. )
end


I got an exception :

caught exception SCP did not finish successfully (1): scp: /root/files/*.log: No such file or directory


But it worked when I copied a specific file

ssh.scp.download!( '/root/files/myfile.log', './files1/' )


Can anyone help?

Thanks!

Answer

I would suggest using net sftp for this as it allows globing directory which is more elegant. Here:

require 'net/sftp'
Net::SFTP.start( scp_hostname, scp_username, :keys => scp_keys, :timeout => 360 ) do |sftp|
    sftp.dir.glob("/remote/path", "*.log") do |file|
      sftp.download!( "/remote/path/#{file.name}", "./files1/#{file.name}" )
    end
end

or with ssh you can use the following trick:

Net::SSH.start( scp_hostname, scp_username, :keys => scp_keys ) do |ssh|
  logfiles = ssh.exec!( 'ls /remote/path/*.log' ).split
  logfiles.each { |file|
    ssh.scp.download!( file, file )
  }
end
Comments