Lua Requires Chilkat v11.0.0+
Lua
SFTP Read Directory Listing
See more SFTP Examples
Demonstrates how to download a directory listing and iterate over the files.Chilkat Lua Downloads
local chilkat = require("chilkat")
-- This requires the Chilkat API to have been previously unlocked.
-- See Global Unlock Sample for sample code.
-- Important: It is helpful to send the contents of the
-- sftp.LastErrorText property when requesting support.
local sftp = chilkat.SFtp.new()
-- Set some timeouts, in milliseconds:
sftp.connect_timeout_ms = 5000
sftp.idle_timeout_ms = 10000
-- Connect to the SSH server.
-- The standard SSH port = 22
-- The hostname may be a hostname or IP address.
local hostname = "www.my-sftp-server.com"
local port = 22
local success = sftp:connect(hostname, port)
if not success then
print(sftp.last_error_text)
return
end
-- Authenticate with the SSH server. Chilkat SFTP supports
-- both password-based authenication as well as public-key
-- authentication. This example uses password authenication.
success = sftp:authenticate_pw("myLogin", "myPassword")
if not success then
print(sftp.last_error_text)
return
end
-- After authenticating, the SFTP subsystem must be initialized:
success = sftp:initialize_sftp()
if not success then
print(sftp.last_error_text)
return
end
-- Open a directory on the server...
-- Paths starting with a slash are "absolute", and are relative
-- to the root of the file system. Names starting with any other
-- character are relative to the user's default directory (home directory).
-- A path component of ".." refers to the parent directory,
-- and "." refers to the current directory.
local handle = sftp:open_dir(".")
if not sftp.last_method_success then
print(sftp.last_error_text)
return
end
-- Download the directory listing:
local dirListing = chilkat.SFtpDir.new()
success = sftp:read_dir_listing(handle, dirListing)
if not success then
print(sftp.last_error_text)
return
end
-- Close the handle for the directory listing.
success = sftp:close_handle(handle)
if not success then
print(sftp.last_error_text)
return
end
-- Iterate over the files.
local fileObj = chilkat.SFtpFile.new()
local i = 0
local n = dirListing.num_files_and_dirs
while i < n do
success = dirListing:file_at(i, fileObj)
if not success then
print(dirListing.last_error_text)
return
end
print(fileObj.filename)
print(fileObj.file_type)
print("Size in bytes: " .. fileObj.size32)
print("----")
i = i + 1
end
print("Success.")