How to Connect to SFTP and FTP

In this tutorial, we will cover how you can connect to a SFTP/FTP server using the translator.

Note: For building SFTP/FTP connections using a pre-built component refer to the From FTP documentation.

For building SFTP/FTP connections in the translator:

Use the net.sftp.init{} command to initialize the connection. You are only required to use the following five parameters:

Parameter

Description

Parameter

Description

Server

The server to connect to. string

Username

The remote user to login as. string

Password

The password to authenticate with. string

Port

The port to use (default = 22). integer

Timeout

Timeout for operations (default = 15 seconds). integer

Your net.sftp.init{} code will look something like this:

local Conn = net.sftp.init{ server=Destination_HostName, username=Destination_Login, password=Destination_Password, port=Destination_Port, timeout = 60, }

For optimal security, use TLS/SSL enabled connections. See Enable TLS/SSL with the Network Client APIs.

When working with files Here is a sample script showing how you can use the net api to List, Get and Put a file via SFTP:

function main(Data) -- (1) Initialize Connection local Conn = net.sftp.init{ server=Destination_HostName, username=Destination_Login, password=Destination_Password, port=Destination_Port, timeout = 60, } -- (2) List files from SFTP Server local list = Conn:list{remote_path="/"} -- (3) Get a file from the SFTP server local get = Conn:get{remote_path='afile.txt'} -- (4) Put a file on the SFTP Server local put = Conn:put{remote_path='sample.txt', data=Data} end

Use io.read() to read the files received or io.write() to process accordingly. Always close file handles to reduce the overhead of unclosed connections. See Local File Operations and the FIL Library.

Once processing is complete you can will typically want to move or delete the the files to avoid reprocessing.

For this, the net API supports renaming and removing files – net.*.rename(),  net.*.delete().

Moving Files:

local fileName = 'afile.txt' local newDirectory = '/processed/'..fileName Conn:rename{old_path=sourcePath, new_path=newDirectory} iguana.logInfo("File moved to "..newDirectory)

Deleting Files:

Â