SFTP删除许可拒绝



我正在使用SFTP客户端从SFTP服务器获取文件。我能够成功阅读该文件并存储它,但是在保存后,我不可能从SFTP服务器中删除它。

代码

require 'net/sftp'
class Sftp
  def self.save
    Net::SFTP.start(somehost, ****, password: ****) do |sftp|
      sftp.dir.foreach("/files") do |entry|
        next unless entry.file?
        file_name = entry.name
        source_file = "/files/#{file_name}"
        destination_file = "tmp/#{file_name}"
        sftp.download!(source_file, destination_file)
        df = File.open(destination_file, "r")
        file_data = df.read
        # Some logic to utilise read file info. in variable "file_data"
        File.delete(df) # deleted from tmp
        sftp.remove!(source_file) # deleted from sftp server
      end
    end
  end
end

执行行sftp.remove!(source_file)时,我会得到错误:

" net :: sftp :: statusexception(3," clibrission dened ")

文件的权限目录

drwxr-xr-x  2 root    root    4096 Dec 22 10:54 files

文件中的文件的权限目录:

drwxr-xr-x 2 root root   4096 Dec 22 10:54 .
drwxr-xr-x 4 root root   4096 Dec 18 15:29 ..
-rwxrwxrwx 1 root root 749199 Dec 18 14:39 a.pdf
-rwxrwxrwx 1 root root   7945 Dec 18 15:41 b.pdf
-rwxrwxrwx 1 root root   7945 Dec 22 10:54 c.pdf

编辑

我更换了以下代码

sftp.remove!(source_file)

sftp.send(:exec, "sudo rm /var/sftp/#{source_file}")

现在,删除有效,但仅适用于第一个文件。然后循环退出而没有任何错误。

可能是什么原因?

我假设您是作为用户以外的用户登录到远程主机。这是正确的吗?

您的问题是root是远程主机上这些文件的所有者,作为root以外的用户,您无权删除它们。

如果您控制了远程文件,则可能需要由其他用户以外的用户保存它们 - 您可以登录以删除它们,但其他人则不能,假设您不希望别人能够删除文件。

如果您以root登录到该服务器,则应能够删除文件。

关于此代码:

df = File.open(destination_file, "r")
file_data = df.read
File.delete(df) # deleted from tmp

这是完成删除文件的过于复杂的方法。您正在将文件的数据读取到file_data中,但没有对其进行任何操作。另外,无需打开文件即可删除它 - 您可以在filespec上调用 File.delete而不是文件对象。

最新更新