I am trying to create multiple directories at once. Currently, the sftp.mkdir! path
only creates one directory level at a time. For example, I can create /test
, and then have to make another directory /test/secure_token
and so on so forth. Is there a way I can create /test/secure_token
in one call rather than two?
Asked
Active
Viewed 574 times
2

smmr14
- 161
- 1
- 1
- 3
2 Answers
1
I did not manage to find a solution for this, so created the following method:
def sftp_makedirs(sftp, remotedir)
return if remotedir == "."
return if sftp.file.directory?(remotedir)
raise StandardError, "path '#{remotedir}' already exists, but not a dir"
rescue Net::SFTP::StatusException #(2, "no such file")
sftp_makedirs(sftp, File.dirname(remotedir))
sftp.mkdir!(remotedir)
end
How it works:
- It terminates the recursion when reaching the empty-path (current-dir aka .)
- It terminates if the directory exists
- It raises an exception if the path exists but is not a directory
- If the path does not exist, it makes sure its base exists, and creates the last level of the path

Vajk Hermecz
- 5,413
- 2
- 34
- 25
-
Thank you sir! for some reason the documentation mislead on this issue – umair.ashfr Jun 21 '23 at 08:27
-1
I ran the following ruby script with host, username, and password passed as command line arguments:
require 'net/sftp'
Net::SFTP.start(host, username, password: password) do |sftp|
sftp.mkdir!("/home/#{username}/test/test2")
end
And was able to successfully create a multi-level directory on the remote host.
The rubydoc doesn't mention that #mkdir! cannot create multi-level directories, and it even gives an example argument as "/path/to/directory"
https://www.rubydoc.info/github/net-ssh/net-sftp/Net%2FSFTP%2FSession:mkdir!
You shouldn't have trouble if you just pass the entire path of the directory you're trying to create, so perhaps it's a weird quirk of your remote host? Hard to say without additional information.

Joshua Pereira
- 191
- 1
- 7