LoginSignup
4
2

More than 5 years have passed since last update.

fabricで鍵認証をセットする

Posted at

chefとかfabricとか使ってると、いちいちサーバログイン時に認証を聞かれるのが面倒だし、公開鍵認証で行けたらいいなぁ、と思うことがあります。

通常は ssh-copy-id を使えばいいと思うんですが、fabricで事前にセットアップしたホスト一覧があるならこういうのも便利かと思うので、作ってみます。

ゴリゴリに書いてますが、一応登録済みキーでないか確認して追加しています。

from fabric.api import *

@task
def copy_id(file="~/.ssh/id_rsa.pub"):
    """Identityをauthorized_keysに追加する"""
    put(file, "/tmp/id.pub")
    try:
        run("if [ ! -d ~/.ssh ]; then mkdir -p ~/.ssh; fi")
        run("if [ ! -f ~/.ssh/authorized_keys ]; then cp /tmp/id.pub ~/.ssh/authorized_keys && chmod 0600 ~/.ssh/authorized_keys; fi")
        run("cat ~/.ssh/authorized_keys /tmp/id.pub | sort -u > /tmp/uniq.authorized_keys")
        run("if [ `cat ~/.ssh/authorized_keys | wc -l` -lt `cat /tmp/uniq.authorized_keys | wc -l` ]; then cat /tmp/id.pub >> ~/.ssh/authorized_keys; fi")
    finally:
        run("rm -f /tmp/id.pub /tmp/uniq.authorized_keys")

通常の鍵認証( ~/.ssh/id_rsa.pub )であれば特に引数は必要ないですが、もし特定の鍵ファイルを使いたい場合も対応できます。ちなみに鍵を作る部分( ssh-keygen )は含んでいません。自分で作ってくださいね。

fab -H target copy_id:file=~/.ssh/custom_id.pub
4
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2