Skip to content
Platform > Plugins

SSH and SFTP Datasources

The SSH plugin is a connector that adds 2 datasource types to the Center: SFTP, which lists, reads, moves, and writes files on an SFTP server, and SSH, which runs a command on a remote host and returns its output as a table.

Prerequisites

  • An account on an SFTP or SSH server that meets the server requirements.
  • Access to the AMIDB Shell Tool, where the statements on this page are run: in the Web at Dashboard -> AMIDB Shell Tool, or over SSH to the Center's database console port, ami.db.console.port (default 3290):

    ssh -p 3290 demo@localhost
    

Getting started: reading a file from an SFTP server

This task installs the plugin, enables the SFTP type, which is switched off by default, and lists a directory on the remote server.

  1. Download the plugin titled "ssh" from the client portal. The download is a file named amissh.tar.gz.
  2. Copy amissh.tar.gz into the installation's plugins/ directory. Do not extract it. See Installing Plugins.

  3. Add this line to config/local.properties:

    # The shipped list without !SFTP. Also remove !SSH to enable the SSH type.
    ami.datasource.plugins=*, !SHELL, !RESTAPI, !SSH
    

    The shipped value is *, !SHELL, !RESTAPI, !SSH, !SFTP. An exclusion always wins over the rest of the list, so appending the type, as in $${ami.datasource.plugins},SFTP, leaves it switched off. Restate the list without the exclusion instead. See Enabling and Disabling Plugins.

  4. Restart the server.

  5. Check that the type is enabled:
    • SHOW DATASOURCE_TYPES; returns a row for SFTP.
    • The server log has CREATED PLUGIN: DATASOURCE>SFTP. A REGISTERED PLUGIN line on its own means the plugin is installed but still excluded.
  6. Register a datasource for the server, replacing the host, port, user name, and password with your own:

    CALL __ADD_DATASOURCE("PricesSftp", "SFTP", "sftp.example.com:22", "sftpuser", "sftppassword", null, null, null);
    
  7. List a directory on the server:

    USE ds="PricesSftp" EXECUTE ls incoming;
    
  8. Check that the query returns one row for each entry in incoming, including . and .., with the columns Name, Size, ModifiedOn, AccessedOn, and Permissions.

The datasource is kept by the Center and is still registered after a restart.

Server requirements

The plugin's SSH library supports only the algorithms below, so the server must enable at least one key exchange method and one host key type from each list.

Negotiated item What the plugin offers
Key exchange diffie-hellman-group-exchange-sha1, diffie-hellman-group14-sha1, diffie-hellman-group1-sha1
Host key ssh-rsa, ssh-dss
Cipher aes128-ctr, aes192-ctr, aes256-ctr, blowfish-ctr, aes128-cbc, aes192-cbc, aes256-cbc, blowfish-cbc, 3des-ctr, 3des-cbc
MAC hmac-sha1-96, hmac-sha1, hmac-md5-96, hmac-md5

All 3 key exchange methods use SHA-1. OpenSSH 9.2, at its default settings, offers none of them and no ssh-rsa host key, so the plugin cannot connect to it. The connection fails during the handshake, before any credentials are sent (see Key exchange was not finished).

To accept the plugin, an OpenSSH server needs these lines in its sshd_config:

1
2
3
# Add one SHA-1 key exchange method and the ssh-rsa host key to the server's defaults
KexAlgorithms +diffie-hellman-group14-sha1
HostKeyAlgorithms +ssh-rsa

The ciphers aes128-ctr, aes192-ctr, and aes256-ctr and the MAC hmac-sha1 are in OpenSSH's defaults.

Registering a datasource

A datasource is registered with __ADD_DATASOURCE, which takes the datasource name, the type, the server's address, the login, and an options string.

  1. Run __ADD_DATASOURCE with the arguments in the table below, e.g:

    CALL __ADD_DATASOURCE("PricesSftp", "SFTP", "sftp.example.com:2222", "sftpuser", "sftppassword", "authMode=keyboardInteractive", null, null);
    
  2. Check that SHOW DATASOURCES; lists the datasource, with the URL as entered and the password stored encrypted.

To change a datasource, call __UPDATE_DATASOURCE with the same arguments as __ADD_DATASOURCE. An argument given as null keeps its current value, so only the arguments being changed need values, e.g: to switch to keyboard-interactive login:

CALL __UPDATE_DATASOURCE("PricesSftp", null, null, null, null, "authMode=keyboardInteractive", null, null);

The password is kept unless a new one is given. An unknown name fails with DATASOURCE not found: '<name>'. Remove a datasource with CALL __REMOVE_DATASOURCE("<name>");.

Argument Value for these types
Name Any name. Queries refer to it as USE ds="<name>".
DatasourceType SFTP or SSH, in capitals.
URL The server's host name, or the host name and port as host:port. The port defaults to 22. Nothing else: no scheme, path, or directory.
Username The account to log in as.
Password The account's password, or the passphrase of the key file in publicKeyFile.
Options Comma-separated key=value pairs from the table below, or null.
RelayId null to run on the Center, or the id of a Relay to run the queries there (see Running on a Relay).
PermittedOverrides null.

The URL has no place for a remote directory. A URL with anything after the port, such as sftp.example.com:22/incoming, is accepted when the datasource is registered, and every query on it then fails with Invalid url format, port should be a number. Give remote paths in each query instead: relative paths start from the account's login directory.

Options

Option Values What it sets
publicKeyFile Path to a private key file in PEM format Logs in with that key instead of a password. Despite the option's name, the file is the private key. The datasource password is used as the key's passphrase. When set, authMode is ignored.
authMode password (default) or keyboardInteractive How the password is sent. Use keyboardInteractive for servers that only accept keyboard-interactive login.
useDumbPty true or false (default) Runs SSH commands with a terminal. Use it for commands that need one, such as a script that checks whether its output is a terminal. With it, the command's error output is returned in the stdout table, and stderr is empty.

The key file has these requirements:

  • PEM format: the file starts with -----BEGIN RSA PRIVATE KEY-----. A key in OpenSSH's own format, which starts with -----BEGIN OPENSSH PRIVATE KEY----- and is what ssh-keygen writes by default, fails with Authentication failed. Create a PEM key with ssh-keygen -t rsa -m PEM, or convert an existing one with ssh-keygen -p -m PEM -f <keyfile>.
  • Inside a permitted directory: the Center reads only files under the directories in ami.component.allowed.dirs, which by default is the installation directory (see Troubleshooting Plugins). A relative path is resolved from the installation directory.
  • Forward slashes in a Windows path: e.g: publicKeyFile=C:/keys/sftp_key.pem. Backslashes in the options string are removed when the datasource is registered, without an error.
  • No passphrase: for a key without a passphrase, pass null as the password.

Registering from the Data Modeler

A datasource can also be registered from the Web, in Editor mode (Ctrl+d). The dialog tests the connection before adding the datasource, and shows the cause of a failure directly.

  1. Navigate to Dashboard -> Data Modeler and select "Attach Datasource".
  2. In the "Add Datasource" dialog, select the "SFTP" tile.
  3. On the "Configuration" tab, fill in the fields:

    Field Default What it sets
    "Name:" Empty The datasource name
    "URL:" Empty host or host:port, as for __ADD_DATASOURCE. The hint under the field reads hostname:optional_port_number
    "Username:" Empty The account to log in as
    "Password:" Empty The account's password, or the key file's passphrase
    "Relay To Run on:" <No Relay, Run on Center> Leave the default to run on the Center, or pick a Relay (see Running on a Relay)
    "Skip Test and force Add" Off Leave off, so the connection is tested first
  4. On the "Advanced" tab, set any options. Each field is one option from the Options table, and an empty field leaves the option unset:

    Field Option
    "auth Mode" authMode
    "public Key File" publicKeyFile
    "use Dumb Pty" useDumbPty
  5. Select "Add Datasource".

  6. Check that the dialog reports Success: Added datasource. Found 5 tables. The tables are the plugin's sample queries.

If the test fails, the dialog shows the cause, such as publicKeyFile not found: followed by the path, and nothing is added. The "Security" tab lists the fields that can be overridden at runtime and needs no change.

SFTP commands

An SFTP query is a command and its arguments, not SQL. Arguments are separated by spaces.

Command Result
ls [path] or dir [path] One row per entry, including . and ..: Name, Size, ModifiedOn, AccessedOn, Permissions. The path defaults to the login directory.
get <file> [<file> ...] One row per file: Name, and Data holding the file's contents as binary.
mkdir <directory> Creates the directory. Returns no rows.
mv <source> <target> Moves or renames a file. Returns no rows.

Any other command returns no rows and no error, and does nothing. There is no delete command: where the account also allows a shell, an SSH datasource can remove a file with rm (see Running remote commands).

Warning

Do not select files by the dates ls returns. Both date columns are wrong for any file changed after January 1970. Where the account also allows a shell, run ls -l through an SSH datasource to read file times.

Reading a file into rows

get returns a file's contents as one binary value, so a delimited file has to be converted to text and split into rows. This example loads a comma-separated price file into a table.

The file, incoming/prices.csv on the server:

1
2
3
4
5
6
symbol,price
AAPL,189.25
MSFT,402.10
IBM,171.84
GOOG,141.62
AMZN,178.03

Run all steps in one AMIDB Shell Tool session:

  1. Create the target table:

    CREATE PUBLIC TABLE Prices(Symbol String, Price Double);
    
  2. Fetch the file into a session table. raw is created without PUBLIC, so it exists only in this session:

    CREATE TABLE raw AS USE ds="PricesSftp" EXECUTE get incoming/prices.csv;
    
  3. Convert the contents to text, split them into lines and fields, and insert each line after the header:

    String t = SELECT binaryToStr(Data) FROM raw; List ls = strSplitLines(t); for (int i = 1; i < ls.size(); i++) { String ln = (String)ls.get(i); if (strIsnt(ln)) continue; List p = strSplit(ln, ","); INSERT INTO Prices VALUES ((String)p.get(0), (Double)p.get(1)); }
    

    binaryToStr converts the binary value to text. Casting it with (String) returns a label such as 72 bytes, not the contents.

  4. Check that SELECT * FROM Prices; returns 5 rows.

The Prices table is kept after a restart, but its rows are not. To keep the rows, create the table with a persist engine (see Realtime Tables).

Writing a file

An INSERT into an SFTP datasource writes a file on the server, named by the target table:

USE ds="PricesSftp" INSERT INTO `outgoing/prices_copy.txt` USE ds="AMI" EXECUTE SELECT Symbol, Price FROM Prices;

The file is pipe-delimited: a line of column names, a line of column types, then one line per row. Text values are in double quotes, a null is written as null, and a binary value is written as its raw bytes followed by the line separator; the type line names a binary column Bytes. Lines end with the Center host's line separator, which is CRLF on Windows. For the example above:

1
2
3
4
5
6
7
Symbol|Price
String|Double
"AAPL"|189.25
"MSFT"|402.1
"IBM"|171.84
"GOOG"|141.62
"AMZN"|178.03

Because the 2 header lines are always written, an INSERT cannot upload a file such as a PDF unchanged: the header lines end up in front of its contents.

Warning

Write to a file name that does not exist yet. If the file already exists and the new content is shorter, the old file's remaining lines stay at the end. To replace a file, first move the old one aside with mv; the SFTP type cannot delete the moved file afterwards.

Reading large files

get reads a file in requests of 33991 bytes, which is also the largest request the plugin accepts. A larger file is read in several requests. Set a smaller request size for one query with the _bufsize directive:

USE ds="PricesSftp" _bufsize=8192 EXECUTE get incoming/prices.csv;

A _bufsize above 33991 makes get fail on any file larger than 33991 bytes (see Illegal sftp packet len). On a smaller file it appears to work, so test a changed _bufsize with a large file.

Running remote commands (SSH)

An SSH query runs one command on the remote host, given in the _cmd directive, such as a health-check script whose output should come back as a table. The query after EXECUTE reads the output from a table named cmd, and the result tables are titled stdout, stderr, and exitcode. This task reads the same price file by running cat on the server.

  1. Enable the type: remove !SSH from ami.datasource.plugins in config/local.properties, then restart the server.
  2. Register a datasource of type SSH:

    CALL __ADD_DATASOURCE("PricesSsh", "SSH", "sftp.example.com:22", "sftpuser", "sftppassword", null, null, null);
    
  3. Run the command and parse its output:

    USE ds="PricesSsh" _cmd="cat incoming/prices.csv" _capture="stdout" _delim="," _fields="String symbol, Double price" _skipLines=1 _linenum="" EXECUTE SELECT * FROM cmd;
    
  4. Check that the query returns one table, titled stdout, of 5 rows with the columns symbol and price.

Without _capture, the query returns 3 tables: stdout, stderr, and exitcode, which holds one exitCode column. Without _linenum="", the stdout and stderr tables also have a linenum column holding the line number.

Showing the output on a dashboard

A command's output can be shown as a table in the Web, so people who do not use the AMIDB Shell Tool can see it, e.g: a health check on a remote host. This task needs an SSH datasource, such as PricesSsh above, and builds a datamodel on it and a table panel on that datamodel.

  1. In Editor mode (Ctrl+d), navigate to Dashboard -> Data Modeler, right-click the SSH datasource under "Datasources", and select "Add Datamodel to" followed by its name.
  2. In "AMI Table Chooser", select the sample table, then select "Next >>".
  3. Replace the script in the editor with the command to run. There is no ds=: the datamodel's "Data source:" field already names the datasource.

    1
    2
    3
    {
      CREATE TABLE Health AS USE _cmd="df -h /" _capture="stdout" _linenum="" EXECUTE SELECT * FROM cmd;
    }
    
  4. Fill in the fields below the editor, then select "Test":

    Field Default What it sets
    "Name:" sample The datamodel's name, e.g: Health
    "Data source:" The datasource chosen in step 1 The SSH datasource the script runs on
    "Auto-Run:" On Startup Runs the datamodel when the layout loads
  5. Check that the "Tables" tab under the editor lists Health with the command's output, then select "Finish".

  6. In the Data Modeler graph, right-click the new datamodel and select "Add Table / Visualization / Form". On the "Grid" tab, select "Table", then select "Submit".
  7. Check that a window opens with a table titled Health, holding one row per line of the command's output.

SSH directives

Directive Default What it sets
_cmd None, required The command line to run on the remote host.
_stdin None Text written to the command's standard input.
_capture All 3 Which outputs to return, comma-separated, from stdout, stderr, and exitCode. One table per entry, in the order listed.

The command's standard output and standard error are each parsed the way a flat file is, so the flat-file parsing directives also apply:

  • _fields, _delim, _conflateDelim, _quote, _escape, and _equals, for delimited and key-value lines
  • _pattern and _mappings, for pattern capture and renaming columns
  • _linenum, _skipLines, _filterIn, and _filterOut, for line numbers and selecting lines

Without _fields or _pattern, each line is returned whole in a column named line.

Running on a Relay

A datasource registered with a RelayId is stored on the Center but runs on that Relay: the Center sends each query to the Relay, and the Relay opens the SSH connection from its own host. Use this to reach an SFTP or SSH server that only the Relay's host can reach.

Both the Center and the Relay need the plugin:

  • The Center, to register the datasource: __ADD_DATASOURCE accepts only types enabled on the Center.
  • The Relay, to run it: the Relay builds the datasource from its own plugins, so it needs amissh.tar.gz in its own plugins/ directory and the type enabled in its own ami.datasource.plugins.

In a single AmiCore installation the Center and Relay share one plugins/ directory and one config/local.properties, so one install covers both. A Relay on another host is installed separately. The Relay opens the connection to the Center, not the other way around, so the Relay's host must be able to reach the Center's ami.center.port (default 3270).

To run an SFTP datasource on a Relay on another host:

  1. On the Relay's host, copy amissh.tar.gz into plugins/, and set the Relay's config/local.properties:

    1
    2
    3
    4
    5
    # The Center to connect to
    ami.center.host=<center host>
    ami.center.port=3270
    # Enable the SFTP type on this Relay too
    ami.datasource.plugins=*, !SHELL, !RESTAPI, !SSH
    
  2. Restart the Relay.

  3. Check that the Relay is connected: SELECT RelayId, Hostname FROM __RELAY; returns a row for it.
  4. Register the datasource with the Relay's RelayId:

    CALL __ADD_DATASOURCE("PricesSftpRemote", "SFTP", "sftp.example.com:22", "sftpuser", "sftppassword", null, "<relay id>", null);
    
  5. Check that USE ds="PricesSftpRemote" EXECUTE ls incoming; returns one row per entry. The Relay's log, not the Center's, records the SFTP connection.

If the plugin is missing on the Relay, a query returns no result and no error until the caller times out (90 seconds in the AMIDB Shell Tool). The cause is in the Relay's log, plugin doesn't exist (See property ami.datasource.plugins): SFTP, not the Center's.

Pulling a file on a schedule

A Center timer can run the steps from Reading a file into rows on a schedule, so the file is fetched without anyone running a query. This task loads incoming/prices.csv every weekday evening.

  1. Create a table with a column recording when each row was loaded:

    CREATE PUBLIC TABLE DailyPrices(Symbol String, Price Double, LoadedAt Long);
    
  2. Create the timer. Quotes inside the script are escaped with a backslash:

    CREATE TIMER PullPrices OFTYPE AMISCRIPT ON "0 0 19 * * MON-FRI UTC" USE logging="on" script="CREATE TABLE raw AS USE ds=\"PricesSftp\" EXECUTE get incoming/prices.csv; String t = SELECT binaryToStr(Data) FROM raw; DROP TABLE raw; List ls = strSplitLines(t); long now = timestamp(); for (int i = 1; i < ls.size(); i++) { String ln = (String)ls.get(i); if (strIsnt(ln)) continue; List p = strSplit(ln, \",\"); INSERT INTO DailyPrices VALUES ((String)p.get(0), (Double)p.get(1), now); }";
    
  3. After the timer has run, check that SELECT LoadedAt, count(*) FROM DailyPrices GROUP BY LoadedAt; returns one row per run, each with a count of 5. With logging="on", the Center's log also records Completed timer async: PullPrices for each run.

To test the script without waiting for the schedule, create the timer with ON "5000", which runs it every 5 seconds, then remove it with DROP TIMER PullPrices;. The schedule format, including the crontab form used above, is described in Center Timers.

Files with a date in the name

Daily files usually carry the date in their name, and the dates ls returns cannot be used to find the latest one. Build the name from today's date instead. Inside a timer script, ${name} inserts the value of a variable into the EXECUTE text and into the target file name of an INSERT.

To fetch today's file, e.g: incoming/prices_20261113.csv, start the timer's script with:

String today = formatDate(timestamp(), "yyyyMMdd", "UTC"); CREATE TABLE raw AS USE ds="PricesSftp" EXECUTE get incoming/prices_${today}.csv;

Continue as in Reading a file into rows. Inside script="...", escape each double quote with a backslash, as in the timer above.

${name} is replaced only inside scripts such as timers. Typed directly in the AMIDB Shell Tool, it is sent as written, so the server is asked for a file literally named prices_${today}.csv.

Sending a file on a schedule

A timer can send a file every day by running the INSERT from Writing a file with a dated name, so that each run writes a new file and the overwrite problem described there does not arise.

  1. Create the timer:

    CREATE TIMER SendSummary OFTYPE AMISCRIPT ON "0 30 19 * * MON-FRI UTC" USE logging="on" script="String day = formatDate(timestamp(), \"yyyyMMdd\", \"UTC\"); USE ds=\"PricesSftp\" INSERT INTO `outgoing/summary_${day}.txt` USE ds=\"AMI\" EXECUTE SELECT Symbol, Price FROM Prices;";
    
  2. After the timer has run, check that outgoing/ on the server holds summary_ followed by today's date, e.g: USE ds="PricesSftp" EXECUTE ls outgoing;.

Troubleshooting

Most connection failures show only Uncaught error: Unknown Error in the AMIDB Shell Tool. The cause is in the Center's log, log/AmiCore.log: find the CONCURRENT_EXECUTE_ERROR line naming the datasource, and read the caused by lines below it. The headings below are those causes, and the messages the Shell Tool shows directly.

DATASOURCE_TYPE does not exists: 'SFTP'

Shown by __ADD_DATASOURCE when the type is not enabled. Check that amissh.tar.gz is in plugins/, that ami.datasource.plugins does not contain !SFTP (or !SSH), and that the server was restarted after the change.

plugin doesn't exist (See property ami.datasource.plugins): SFTP

Shown when querying a datasource whose type has since been switched off. Datasources are kept while their type is off. Enable the type again to use them. For a datasource with a RelayId, this message appears in the Relay's log instead, and the query times out (see Running on a Relay).

Invalid url format, port should be a number

Shown when querying a datasource whose URL contains something other than a host and port. Remove the datasource with CALL __REMOVE_DATASOURCE("<name>");, register it again with host or host:port only, and give remote paths in the query.

Key exchange was not finished, connection is closed

In the log, under General Error. The server offers none of the key exchange methods the plugin supports. Enable a SHA-1 key exchange method and the ssh-rsa host key on the server, as in Server requirements.

Connection refused

In the log, under General Error. Nothing is listening at the host and port in the URL. The port defaults to 22 when the URL has none.

Authentication failed

In the log. The server rejected the login. Check the user name and password. For a key file, check that it is in PEM format, that publicKeyFile names the private key, and that the password is its passphrase. A key in OpenSSH format shows Invalid PEM structure, '-----BEGIN...' missing in the log just before Authentication failed.

Access denied by ami_center

In the log, as Access denied by ami_center: followed by the path and not in Permitted dirs. The key file is outside the directories the Center may read. Move it under the installation directory, or add its directory to ami.component.allowed.dirs.

publicKeyFile not found

In the log, followed by the full path the Center looked for. The file named in publicKeyFile does not exist there; a relative path is resolved from the installation directory.

authMode option must be either 'password' or 'keyboardInteractive'

In the log. The authMode option has another value.

Unknown Host

In the log. The host name in the URL does not resolve.

No such file

In the log, as No such file (SSH_FX_NO_SUCH_FILE ...). The path in a get does not exist, or contains a space: an SFTP query is split on spaces.

Illegal sftp packet len

In the log, as Illegal sftp packet len: followed by a number. _bufsize is above 33991 and the file is larger than 33991 bytes.

Attached to disconnected relay

Shown as Datasource '<name>' is attached to disconnected relay: <relay id> when the datasource has a RelayId and that Relay is not connected to the Center. Start the Relay, or check its id with SELECT RelayId FROM __RELAY;.

Unknown variable

Shown as Unknown variable: followed by the datasource name: the name in USE ds= is not quoted. Write USE ds="PricesSftp", not USE ds=PricesSftp.

Unknown directive

Shown as Unknown directive: '<directive>' for datasource type <type>, followed by the directives the type accepts. Directive names are case-sensitive, and the message suggests the right spelling. SSH does not accept _env or _useHostEnv.

The _cmd directive is required

Shown when an SSH query has no _cmd.

Upload to datasource

Shown when an INSERT targets an SSH datasource. Only SFTP datasources accept INSERT.

What this does not support

  • No base directory in the URL: the URL is the host and port only, and any path after the port is refused.
  • No paths with spaces: an SFTP query is split on spaces, so a path with a space cannot be given.
  • No file deletion: the SFTP commands are ls, dir, get, mkdir, and mv; there is no delete.
  • No writes through SSH: an INSERT into an SSH datasource is refused.
  • No environment variables on SSH: _env and _useHostEnv are refused on an SSH datasource.
  • No OpenSSH-format private keys: key files must be in PEM format.
  • No host key checking: the plugin accepts any host key the server presents, so it does not detect a changed or impersonated server.
  • No FTP or FTPS: SFTP is the SSH File Transfer Protocol and does not connect to FTP or FTPS (FTP over TLS) servers.
  • No key exchange newer than SHA-1: key exchange is SHA-1 only, and host keys are ssh-rsa or ssh-dss only (see Server requirements).