[英]Delete a file using Ruby SFTP `remove` and `remove!`
I am trying to old delete files from an FTP using Ruby net/sftp
, but I keep getting an error saying the file does not exist. 我正在尝试使用Ruby net/sftp
从FTP中旧删除文件,但是我一直收到错误消息,指出该文件不存在。
:error=>"Net::SFTP::StatusException (2, \"no such file\")"
I can manually delete files when logging in using the same creds, so I know I have permission. 使用相同的凭据登录时,我可以手动删除文件,所以我知道我有许可。
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
I prefer remove!
我更喜欢remove!
so everything happens synchronously in this case, but I have also tried remove
. 因此在这种情况下,所有操作都是同步发生的,但是我也尝试过remove
。
I also tried giving it the full path of the file instead of just the entry name (like 'somePath' + entry.name
instead of just entry.name
). 我还尝试给它提供文件的完整路径,而不仅仅是输入条目名称(例如'somePath' + entry.name
而不是仅仅entry.name
)。 I was thinking perhaps it was because I needed to change the working directory, which apparently net/sftp
does not allow. 我在想也许是因为我需要更改工作目录,但显然net/sftp
不允许这样做。
Thanks in advance! 提前致谢!
Check if entry
is a directory if yes then use ftp.rmdir
. 检查entry
是否是目录(如果是),然后使用ftp.rmdir
。 like below - 像下面-
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
We were eventually able to delete files using the remove
method (instead of remove!
.) We made a small change to the way we provide the password. 最终,我们能够使用remove
方法(而不是remove!
)删除文件。我们对提供密码的方式进行了小的更改。
We confirmed that permissions on the FTP did not change, so I think using non_interactive: true
may have been the trick. 我们确认FTP的权限没有更改,因此我认为使用non_interactive: true
可能是诀窍。
require 'net/sftp'
def self.delete_report(endpoint, username, password, report_filename)
SSH_OPTIONS = { non_interactive: true }.freeze
report_filename_base = File.basename(report_filename, '.*')
Net::SFTP.start(endpoint, username, SSH_OPTIONS.merge(password: password)) do |sftp|
sftp.remove(report_filename)
sftp.remove("#{report_filename_base}.fin")
sftp.remove("processed/#{report_filename}")
sftp.remove("processed/#{report_filename_base}.fin")
sftp.remove("failed/#{report_filename}")
sftp.remove("failed/#{report_filename_base}.fin")
sftp.remove("failed/#{report_filename_base}.info")
end
I still don't fully understand why the same method did not work before, but we're able to delete files in subfolders too, as shown in this example. 我仍然不完全理解为什么以前无法使用相同的方法,但是我们也能够删除子文件夹中的文件,如本示例所示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.