3

So far as I can tell I need to use both Net::SCP and Net::SSH if I want to copy a file to a remote host and then manipulate it from the command line.

It would be nice to set up one SSH session, do the copy and then use the same connection to unpack the file and install them.

Am I missing something?

Danoram
  • 8,132
  • 12
  • 51
  • 71
Russell Fulton
  • 570
  • 4
  • 17

2 Answers2

7

Net::SCP allows you to easily grab a Net::SCP reference from an existing Net::SSH session:

require "net/ssh"
require "net/scp"
Net::SSH.start("remote.host", "username", :password => "passwd") do |ssh|
  ssh.scp.upload("/local/path", "/remote/path")
  ssh.exec("...insert commands...")
end

Read more here: http://net-ssh.github.io/net-scp/classes/Net/SCP.html

cmrichards
  • 1,725
  • 1
  • 19
  • 28
  • Can I also delete the file from the remote server after it is downloaded? – Nikhil Wagh Oct 11 '19 at 07:06
  • Using the SSH session this should be possible. Simply execute the 'rm' command : 'rm /path/to/file' – cmrichards Oct 11 '19 at 09:11
  • Won't this create the problem of deleting the file before it was even downloaded? Race condition. – Nikhil Wagh Oct 11 '19 at 11:09
  • I'm not sure. You could always wait until the file has finished downloading before deleting it – cmrichards Oct 11 '19 at 11:14
  • In your code how would you know that the file is uploaded/downloaded? Is there something like `channel.on_download_complete`. PS I couldn't find it. I was doing 3 ssh sessions to manipulate file, download file and then delete the file. – Nikhil Wagh Oct 11 '19 at 12:11
  • I could do this ```ssh.scp.download!("/remote/path", "/local/path") ssh.exec("some command")``` But this blocks the flow. I had multiple files to be downloaded. – Nikhil Wagh Oct 11 '19 at 12:13
2

Have you considered Net::SFTP? Along with that and Tempfile, I am currently using it in a project to copy from local to remote. You can also do simple file modifications. If you were so inclined, you could use Stream.IO to edit the file even more.

https://github.com/net-ssh/net-sftp

http://net-ssh.github.io/net-sftp/

MiggityMac
  • 919
  • 9
  • 11