ruby - 如何将文件从一台服务器复制到另一台服务器?

标签 ruby

我有一台服务器,其中只有 xls 日志文件。每个文件为 5-15Mb,并且在文件随时添加的意义上是动态的。现在我需要一种使用 Ruby 执行以下过程的方法。

  1. 通过将文件名从一台只有日志文件的服务器发送到另一台服务器来复制文件。
  2. 我需要将服务器密码作为参数传递。
  3. 一切都在后台发生,由 Ruby 脚本触发。

最佳答案

查看 Net::SCPNet::SSH gem 。第一个让您使用安全副本检索文件,第二个让您轻松找到可用于检索的文件的名称。在 Net::SSH 中,ssh.exec! 将成为您的 friend 。

来自Net::SCP文档:

Net::SCP implements the SCP (Secure CoPy) client protocol, allowing Ruby programs to securely and programmatically transfer individual files or entire directory trees to and from remote servers. It provides support for multiple simultaneous SCP copies working in parallel over the same connection, as well as for synchronous, serial copies.

Net::SCP also provides an open-uri tie-in, so you can use the Kernel#open method to open and read a remote file:

  # if you want to read from a URL voa SCP:
  require 'uri/open-scp'
  puts open("scp://user@remote.host/path/to/file").read

From the Net::SSH docs:

require 'net/ssh'

Net::SSH.start('host', 'user', :password => "password") do |ssh|
  # capture all stderr and stdout output from a remote process
  output = ssh.exec!("hostname")

在上面的代码中添加一个end来关闭这个 block 。在 block 内,output 将包含您发送的命令的结果。

通过 Ruby 从包含文件的机器检索文件的替代方法是让 Ruby 直接从托管文件的机器启动传输并通过 scp 将它们推送到另一台机器。

除了使用 Net::SCP 和 Net::SSH,您还可以使用 Net::SFTP , 在一个 gem 中管理它。它也依赖安全连接,但您可能无法使用 SFTP。 Net::SFTP::Operations::DirNet::SFTP::Operations::Download 类和文档将成为您的 friend 。

其他选项包括在 @tadman 提到的简单 shell 中使用标准 rsync。有多种方法可以实现这一点,这是托管环境中的常见需求。


any other better approach?

rsync,在命令行。它非常智能,可以根据需要移动文件夹和文件增量。此外,“How to transfer files using ssh and Ruby ”及其指向“Ruby file upload ssh intro ”的链接。

将@tadman 的rsync 推荐与Ruby 融合在一起,有“Cheapest rsync replacement (with Ruby)”。

关于ruby - 如何将文件从一台服务器复制到另一台服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8728847/

相关文章:

Ruby:如何计算一个字符串在另一个字符串中出现的次数?

ruby-on-rails - Mongoid 默认范围覆盖默认值。为什么?

ruby - 为什么 Eclipse 错误地发现 Ruby 注释中的拼写错误?

ruby-on-rails - 表单中的 Activemodel 日期验证和分配

ruby - 简单异或 ruby​​ 1.9.2

ruby-on-rails - Rails - 为什么是 "source ' https ://rubygems. org' "giving -bash No such file or directory"

ruby - rubygem elasticsearch的语法错误

ruby - 添加黑盒库以进行 Pry 调试

ruby-on-rails - 在 Ruby on Rails 中使用 chartkick 自定义工具提示

ruby-on-rails - 为什么每个方法都需要将它循环的值分配给一个变量?