2015年8月15日土曜日

[CentOS6] sshの鍵で特定のコマンドを実行する


ssh の公開鍵を使って、任意のコマンドを実行することができます。
まず、以下のようにしてパスフレーズなしの鍵を作ります。以下の例は、rootユーザーにRSA暗号方式の鍵を作成しています。
# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
f9:81:b6:c7:8f:b9:aa:3e:0e:c6:bd:35:19:a1:1e:06 root@centos6
これで、/root/.ssh/ディレクトリに秘密鍵(id_rsa)と公開鍵(id_rsa.pub)が作成されます。 続いて、公開鍵のid_rsa.pubをauthorized_keysというファイルに登録して、パーミションを変更します。
# cd /root/.ssh
# cat id_rsa.pub >> authorized_keys
# chmod 600 authorized_keys
今度は、この authorized_key に登録した公開鍵の先頭に、実行させたい任意のコマンドを記述します。 フォーマットは以下のとおり。
command="実行させたいコマンド",sshのオプションをカンマ区切りで書く
command=xxx というのを付け足すことによって、その公開鍵でアクセスがあったときに指定したコマンドを実行させることができます。
以下の例では、/var/log/messages を表示します。
command="cat /var/log/messages" ssh-rsa CCCCAbAFERTWER....(省略)
これを実行すると以下のようになります。ssh 実行時に上記で作成した秘密鍵を指定します。
# ssh -i id_rsa root@centos6
Apr 17 12:11:46 centos6 ntpd[1006]: synchronized to 210.173.160.27, stratum 2
Apr 17 23:17:06 centos6 ntpd[1006]: synchronized to 210.173.160.87, stratum 2
Apr 18 08:40:32 centos6 ntpd[1006]: synchronized to 210.173.160.27, stratum 2
Apr 18 09:31:48 centos6 ntpd[1006]: synchronized to 210.173.160.87, stratum 2