Search code examples
ruby-on-railsrubysshsftpnet-sftp

Is there any way to get the date modified from Net::SSH or NET::SFTP commands in ruby?


Is there an easy way to get the date modified of a file by using Net::SFTP?

It'd be nice to be able to do this:

Net::SFTP.start('some_server') do |sftp|
  sftp.dir.glob('*').each do |file|
    puts file.mtime
  end
end

But that's not possible (to my knowledge).

Berns.


Solution

  • Your example code is almost there, you just need to use file.attributes.mtime where you had file.mtime.

    Also, I'm guessing the code in the question was just an example, but in order for it to execute you also need to pass the username and password to start and pass the path as well as the pattern to glob. So a working example would be:

    Net::SFTP.start('some_server', 'mike', :password => 'secret') do |sftp|
      sftp.dir.glob('.', '*').each do |file|
        puts file.attributes.mtime
      end
    end
    

    The value returned by mtime will be the number of seconds since the epoch so you may want to pass it to Time.at to convert it to a Time object.

    In case you're curious, the other attributes available in the same way are:

    • permissions
    • uid
    • gid
    • size
    • atime (time of last access)