ruby - 使用 Ruby SFTP 删除文件 `remove` 和 `remove!`

标签 ruby ftp sftp delete-file net-sftp

我正在尝试使用 Ruby net/sftp 从 FTP 删除旧文件,但我不断收到错误消息,指出该文件不存在。

:error=>"Net::SFTP::StatusException (2, \"no such file\")"

使用相同的凭据登录时,我可以手动删除文件,因此我知道我拥有权限。

require 'net/sftp'
ftp = Net::SFTP.start(@ftp_url, @ftp_user, :password =>  @ftp_pwd)
ftp.dir.entries('somePath').each do |entry|
    begin
      age_days = (Time.now.to_i - entry.attributes.atime) / 86400

      if(age_days > ftp_max_file_age_days)
        ftp.remove!(entry.name)
      end

    rescue Exception => e
      # log error here
    end
end

我更喜欢remove!,所以在这种情况下一切都是同步发生的,但我也尝试过remove

我还尝试给它提供文件的完整路径,而不仅仅是条目名称(例如'somePath'+entry.name,而不仅仅是entry.name) 。我在想也许是因为我需要更改工作目录,这显然是 net/sftp 不允许的。

提前致谢!

最佳答案

检查entry是否是一个目录,如果是,则使用ftp.rmdir。就像下面一样 -

require 'net/sftp'
ftp = Net::SFTP.start(@ftp_url, @ftp_user, :password =>  @ftp_pwd)
ftp.dir.entries('somePath').each do |entry|
  begin
    age_days = (Time.now.to_i - entry.attributes.atime) / 86400

    if(age_days > ftp_max_file_age_days)
      if File.directory?(entry.name)
        ftp.rmdir(entry.name) 
      else         
        ftp.remove!(entry.name)
      end
    end

  rescue Exception => e
    # log error here
  end
end

关于ruby - 使用 Ruby SFTP 删除文件 `remove` 和 `remove!`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32150796/

相关文章:

mysql - 在 Wordpress MySQL 数据库中使用凭据进行 SFTP 身份验证?

ruby - 碰撞检测代码应该放在哪里?

ruby - 仅适用于 cron :/usr/bin/env: ruby_executable_hooks: No such file or directory

ruby-on-rails - 通过 Rails 和 pg gem 插入 PostgreSQL 服务器时,“ token "-"无效”

ruby-on-rails - Form_for 嵌套对象

php - ftp_ssl_connect 与隐式 ftp over tls

c# - 线程FTP上传C#

python - 如何使用Python将特定格式的文件从sftp复制到本地

hadoop - 是否可以从 hive create external table 命令导出/创建外部表文件到远程服务器

python - 从 Python 运行 WinSCP 命令