Mitto CMD job - ssh and run command

OpenSSH is installed by default on every Mitto instance. If you have SSH access to another server, it is possible to use a Mitto CMD job to SSH to that server and run commands or scripts.

Test SSH connection with CMD job

Before you begin, it may be useful to check that the server you want to SSH to will allow you to connect. The following CMD job config is useful for this. Replace <ssh destination server hostname> with the hostname or IP address of the server you want to SSH to:

{
    "cmd": "nc -zvw10 <ssh destination server hostname> 22 > /var/mitto/data/ssh-connection-status.txt 2>&1",
    "cmd_env": {},
    "exec": false,
    "shell": true
}

After running this job, check the output of the created file using Mitto’s API in your browser.
https://{mitto_url}/api/file/ssh-connection-status.txt

SSH with a Keyfile

If your SSH connection requires a keyfile, you will need to upload your key to Mitto first. This will require a shell script, and a second CMD job that you will only need to run once.

First, Upload your SSH key to Mitto using the file manager.

Second, Create a CLI Job to Add the Key to Mitto:

The SSH key needs to be moved into /var/mitto/etc/.ssh/ and have the correct permissions chmod 0400 /var/mitto/etc/.ssh/{key}.

Create the following shell script and also upload it via the file manager:

#!/bin/bash

mkdir -p /var/mitto/etc/.ssh/
mv /var/mitto/data/$1 /var/mitto/etc/.ssh/
chmod 0400 /var/mitto/etc/.ssh/$1

In the example below the SSH key is called ssh_key and the shell script called add-ssh-key.sh

Create and run a Mitto command line job running the shell script above with your deploy key as an argument: bash /var/mitto/data/add-ssh-key.sh ssh_key

You will only need to run the above job once.

Finally, Create a CMD job that will SSH using the key and run a command

Create and run a Mitto command line job using a command like the following:

ssh -o StrictHostKeyChecking=no -i /var/mitto/etc/.ssh/ssh_key <username>@<ssh destination server hostname> touch hello.txt

substitute the remote host’s username and hostname/IP above.

This command will SSH, automatically updating the known_hosts file (-o StrictHostKeyChecking=no), using our ssh key (-i /var/mitto/etc/.ssh/ssh_key), and run the command touch hello.txt on the remote server.

If the cmd job runs successfully a file named hello.txt will appear in the remote server user’s home directory.