How can I identify if an item is a file or a directory using Net::SFTP?

1.6k Views Asked by At

How to identify whether the item of a directory is a file or a directory using Net::SFTP or ruby code?

3

There are 3 best solutions below

0
On

At least two ways to do it in SFTP and Ruby:

require 'net/sftp'
Net::SFTP.start('HOSTNAME', 'USER', :password => 'PASSWORD') do |sftp|

  file = File.expand_path(__FILE__)
  dir  = File.dirname(file)

  sftp.lstat!(file).directory?
  sftp.lstat!(dir).file?

  sftp.file.open(dir, "r") do |f|
    f.stat.file?
    f.stat.directory? # true
  end

end
0
On

The do_stat method seems like it could get you that information. See also the documentation for Net::SFTP::Attributes and perldoc -f stat.

0
On

To illustrate the use of Manni's recommendation:

use Fcntl(:mode);

my $permissions  = $sftp->do_stat($path)->perm();
my $is_directory = S_ISDIR($permissions);