Rich SSH
host aliases
Bad title, but nice little trick: you can use ssh
configuration file to define rich shell commands to be executed on a remote host. And here is an example.
Imagine you have a remote host with MySQL server on it, and sometimes you need to go there and execute a statement or two. You could wind up some visual DB admin tool like phpMyAdmin
or DataGrip
, but maybe it’s just some quick query like select count(*) from users
, and simple utility like mysql
would do just fine. So, you probably do something like this (assuming you already have your key-base authentication configured):
$ ssh my.dev.server.com
Last login: Mon Jul 27 02:15:13 2020 from 1.2.3.4
user@my.dev.server.com $ mysql -u username -p
Enter password: ****
mysql> select count(*) from users;
+----------+
| count(*) |
+----------+
| 5 |
+----------+
1 row in set (0.00 sec)
mysql>
Probably opening up DB admin tool would be quicker and less tedious, but let’s try to optimize our console-only approach via ~/.ssh/config
.
First, we can configure ssh to execute our command right away:
Host my.dev.server.com
RemoteCommand mysql -u username -p
RequestTTY yes
This saves us from typing one command — mysql -u username -p
— and also prevents us from using ssh
to establish usual session. Let’s fix that like this:
Host dev mysql.dev
Hostname my.dev.server.comHost mysql.dev
RemoteCommand mysql -u username -p
RequestTTY yes
This adds two aliases to real (long and clumsy) hostname, and by choosing specific alias you can either open normal ssh
connection:
$ ssh dev
Last login: Mon Jul 27 02:35:07 2020 from 1.2.3.4
user@my.dev.server.com $
Or immediately run mysql
:
$ ssh mysql.dev
Enter password: ****
mysql>
To avoid entering password every time you can use ~/my.cnf
on the remote server:
[client]
user=username
password=sEcrEt
Or maybe you have some application running on the server which happens to have .env
file with username/password/database in it, and in this case RemoteCommand
in ~/.ssh/config
can be modified like this:
Host dev mysql.dev
Hostname my.dev.server.comHost mysql.dev
RemoteCommand sh -c '. /path/to/app/.env; mysql -u $DBUSER -p$DBPASS -D $DBNAME'
RequestTTY yes
With this config you can access mysql
utility instantly:
$ ssh mysql.dev
mysql>
In a similar fashion other commands can be aliased, e.g.:
top.dev
:top -o %MEM -d 1
(or whatever other defaults you choose)stats.dev
:docker stats
logs.dev
:tail -f /var/log/syslog
- etc.