Restrict SSH to Run A Specific Command
However, not everyone know (I did not know at first) that you can restrict (or force) the ssh session to just execute a particular command. Below shows you how to generate a specifiy public/private key pair (monitoring, monitoring.pub), include the monitoring.pub public key in the remote authorized_keys and prepend that with "command=....". So next time you ssh into this remote machine with the monitoring key using the -i flag, the remote system will automatically run the command.
I used this technqiue to run some of the monitoring scripts installed across a few remote servers. This provides some form of flexiblity without compromising security.
cd ~/.sshchihung@myhost$ ssh-keygen -t rsa -f monitoringGenerating public/private rsa key pair. Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in monitoring. Your public key has been saved in monitoring.pub. The key fingerprint is: 6c:00:82:a5:b1:38:c0:e1:83:e3:c1:7d:82:48:d2:12 chihung@myhost chihung@myhost$ cat monitoring.pubssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAIEAwyAsd3AkcO2Oi3nN71WCTdSg/HXlyA3m74TBqSiAygE7XanwiyhpspFHtM3QFZhZRoqTjUyXwC1qbJyD2fNA2U7JtxBU1x5FCcDoLEIzVR4qplAN5cVFrN7SS4Ee49RRLDVdVV+RIGZdiDe9dqGfaVAKi1pqmvsDJez8AnjAg0U= chihung@myhost
cd .ssh chihung@remote$ cat authorized_keyscommand="/usr/local/bin/my-monitoring.sh" ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAIEAwyAsd3AkcO2Oi3nN71WCTdSg/HXlyA3m74TBqSiAygE7XanwiyhpspFHtM3QFZhZRoqTjUyXwC1qbJyD2fNA2U7JtxBU1x5FCcDoLEIzVR4qplAN5cVFrN7SS4Ee49RRLDVdVV+RIGZdiDe9dqGfaVAKi1pqmvsDJez8AnjAg0U= chihung@myhost chihung@remote$ ls -l authorized_keys-rw------- 1 chihung chihung 264 Aug 19 21:37 authorized_keys chihung@myhost$ ssh -i ~/.ssh/monitoring chihung@remote... ...
PS. Thanks to Ben who highlighted the security loophole in the remote authorized_keys. See comment