我正在尝试使用 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/