如何使用Net :: SFTP和Ruby检查条目是文件还是目录

时间:2016-12-17 22:39:01

标签: ruby sftp

使用Net::SFTPdir我试图确定哪些条目是文件与目录。不知道该在这里查看:

Net::SFTP.start(server_ip, ftp_username, :password => ftp_password, :port => ssh_port, :timeout => 6) do |sftp|
        files = sftp.dir.entries(path).select{|entry| ??? }
        directories = sftp.dir.entries(path).select{|entry| ??? }
end

1 个答案:

答案 0 :(得分:3)

解决方案

您可以使用:

files, directories = sftp.dir.entries(path).partition{ |entry| entry.file? }

实施例

p files.map(&:name)
# ["Gemfile", "Gemfile.lock", ".gitignore", "README.rdoc", "Rakefile", "sftp_pv.expect", "config.ru"]
p directories.map(&:name)
# ["data", "config", "..", "app", "tmp", "public", "vendor", "test", ".git", ".", "log", "bin", "lib", "db"]

如何找到解决方案?

我复制了您的代码,定义了连接到个人服务器所需的所有变量,并将path定义为远程Rails项目。

我将您的区块更改为p sftp.dir.entries(path).first

出来了:

#<Net::SFTP::Protocol::V01::Name:0x00000000dbf3f8 @name="data", @longname="drwxr-xr-x    2 dev      dev         20480 Oct 27 10:45 data", @attributes=#<Net::SFTP::Protocol::V01::Attributes:0x00000000dbf5b0 @attributes={:size=>20480, :uid=>1002, :gid=>1003, :permissions=>16877, :atime=>1482015468, :mtime=>1477557907}>>

通过Google Net::SFTP::Protocol::V01::Name搜索documentation

directory?file?是有前途的名字!

这:

p sftp.dir.entries(path).first.file?

返回false

最后,我记得使用partition可以缩短rejectselectSO Questions的缩写:

  

返回两个数组,第一个包含enum的元素   块评估为true,第二个包含其余部分。