Lua
Lua
Open a Remote Directory on an SFTP Server
See more SFTP Examples
Demonstrates the Chilkat SFtp.OpenDir method, which opens a remote directory and returns a handle for reading its entries. The only argument is the directory path. Close the handle with CloseHandle when finished.
Background: Listing a directory in SFTP is a handle-based operation, mirroring file access: open the directory to get a handle, read its entries, then close it. The handle is passed to
ReadDirListing to retrieve the names and attributes. As with file handles, the directory handle is a server-side resource that should be closed to avoid exhausting the server's limits.Chilkat Lua Downloads
local chilkat = require("chilkat")
-- Demonstrates the SFtp.OpenDir method, which opens a remote directory and returns a handle for
-- reading its entries. The only argument is the directory path.
local sftp = chilkat.SFtp.new()
-- Connect, authenticate, and initialize the SFTP subsystem.
local port = 22
local success = sftp:connect("sftp.example.com", port)
if not success then
print(sftp.last_error_text)
return
end
-- Normally you would not hard-code the password in source. You should instead obtain it
-- from an interactive prompt, environment variable, or a secrets vault.
local password = "mySshPassword"
success = sftp:authenticate_pw("mySshLogin", password)
if not success then
print(sftp.last_error_text)
return
end
success = sftp:initialize_sftp()
if not success then
print(sftp.last_error_text)
return
end
-- Open the remote directory. OpenDir returns a handle string.
local handle = sftp:open_dir("subdir")
if not sftp.last_method_success then
print(sftp.last_error_text)
return
end
print("Opened directory, handle = " .. handle)
-- The directory entries are read with ReadDirListing using this handle.
-- Close the handle when finished.
success = sftp:close_handle(handle)
if not success then
print(sftp.last_error_text)
return
end
sftp:disconnect()