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(default3290):
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.
- Download the plugin titled "ssh" from the client portal. The download is a file named
amissh.tar.gz. -
Copy
amissh.tar.gzinto the installation'splugins/directory. Do not extract it. See Installing Plugins. -
Add this line to
config/local.properties: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. -
Restart the server.
- Check that the type is enabled:
SHOW DATASOURCE_TYPES;returns a row forSFTP.- The server log has
CREATED PLUGIN: DATASOURCE>SFTP. AREGISTERED PLUGINline on its own means the plugin is installed but still excluded.
-
Register a datasource for the server, replacing the host, port, user name, and password with your own:
-
List a directory on the server:
-
Check that the query returns one row for each entry in
incoming, including.and.., with the columnsName,Size,ModifiedOn,AccessedOn, andPermissions.
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:
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.
-
Run
__ADD_DATASOURCEwith the arguments in the table below, e.g: -
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:
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 whatssh-keygenwrites by default, fails withAuthentication failed. Create a PEM key withssh-keygen -t rsa -m PEM, or convert an existing one withssh-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
nullas 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.
- Navigate to Dashboard -> Data Modeler and select "Attach Datasource".
- In the "Add Datasource" dialog, select the "SFTP" tile.
-
On the "Configuration" tab, fill in the fields:
Field Default What it sets "Name:" Empty The datasource name "URL:" Empty hostorhost:port, as for__ADD_DATASOURCE. The hint under the field readshostname: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 -
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 -
Select "Add Datasource".
- 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:
Run all steps in one AMIDB Shell Tool session:
-
Create the target table:
-
Fetch the file into a session table.
rawis created withoutPUBLIC, so it exists only in this session: -
Convert the contents to text, split them into lines and fields, and insert each line after the header:
binaryToStrconverts the binary value to text. Casting it with(String)returns a label such as72 bytes, not the contents. -
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:
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:
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:
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.
- Enable the type: remove
!SSHfromami.datasource.pluginsinconfig/local.properties, then restart the server. -
Register a datasource of type
SSH: -
Run the command and parse its output:
-
Check that the query returns one table, titled
stdout, of 5 rows with the columnssymbolandprice.
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.
- In Editor mode (Ctrl+d), navigate to Dashboard -> Data Modeler, right-click the
SSHdatasource under "Datasources", and select "Add Datamodel to" followed by its name. - In "AMI Table Chooser", select the
sampletable, then select "Next >>". -
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. -
Fill in the fields below the editor, then select "Test":
Field Default What it sets "Name:" sampleThe datamodel's name, e.g: Health"Data source:" The datasource chosen in step 1 The SSHdatasource the script runs on"Auto-Run:" On StartupRuns the datamodel when the layout loads -
Check that the "Tables" tab under the editor lists
Healthwith the command's output, then select "Finish". - 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".
- 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_patternand_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_DATASOURCEaccepts 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.gzin its ownplugins/directory and the type enabled in its ownami.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:
-
On the Relay's host, copy
amissh.tar.gzintoplugins/, and set the Relay'sconfig/local.properties: -
Restart the Relay.
- Check that the Relay is connected:
SELECT RelayId, Hostname FROM __RELAY;returns a row for it. -
Register the datasource with the Relay's
RelayId: -
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.
-
Create a table with a column recording when each row was loaded:
-
Create the timer. Quotes inside the script are escaped with a backslash:
-
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. Withlogging="on", the Center's log also recordsCompleted timer async: PullPricesfor 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:
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.
-
Create the timer:
-
After the timer has run, check that
outgoing/on the server holdssummary_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
SFTPquery is split on spaces, so a path with a space cannot be given. - No file deletion: the
SFTPcommands arels,dir,get,mkdir, andmv; there is no delete. - No writes through
SSH: anINSERTinto anSSHdatasource is refused. - No environment variables on
SSH:_envand_useHostEnvare refused on anSSHdatasource. - 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:
SFTPis 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-rsaorssh-dssonly (see Server requirements).