5
5

More than 5 years have passed since last update.

bitbucketをhttps接続から(id_rsa以外の鍵で)ssh接続するように変更する手順(mac)

Last updated at Posted at 2018-02-09

はじめに

gitのリポジトリにはsshキーを使用して接続するのが一般的です。
ここで作成した公開鍵は他の用途にも利用して問題ないものですので、他のサーバーに接続する時にも利用するのが一般的です。

とはいえ初めはhttps接続でgitを始めると思うので、https接続からssh接続に変更するタイミングはいずれやってきます。

その際の手順についてまとめます。
※macでの設定方法です

手順

SSH鍵の生成

まずはじめにSSH接続するための鍵を作成します。

githubの提示する手順を参考にしています。

ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

オプションの説明
-b: bit数。デフォルトは2048。高い方が解読されにくい。
-t: 生成する鍵の種類。
-C: コメント。

実行すると次のように聞かれます。

Enter a file in which to save the key (/Users/you/.ssh/id_r
sa): 

これに対して、作成する鍵ファイル(今回はother_id_rsaとします)の絶対パスを入力します。

/Users/you/.ssh/other_id_rsa

その後passphraseを登録すると
/Users/you/.ssh/other_id_rsa/Users/you/.ssh/other_id_rsa.pubが作成されます。
前者が秘密鍵(絶対公開してはいけません)、後者が公開鍵になります。

bitbucket / github にSSHキーを登録

githubの提示する手順
bitbucketの提示する手順
を参考にしています。

下記コマンドでクリップボードに公開鍵(ただのテキスト)をコピーします。

pbcopy < ~/.ssh/other_id_rsa.pub

githubやbitbucketのSSH鍵設定画面でペーストし、登録します。

bitbucket / github への接続方法をhttps接続からssh接続に変更する

まずは現状の設定の確認のために下記のコマンドを実行して下さい。

git remote -v

下記のように表示されればssh接続になっているので設定は不要です。

origin  git@bitbucket.org:your-organization/example.git (fetch)
origin  git@bitbucket.org:your-organization/example.git (push)

下記のように表示されるとhttp接続になっているので、originのURLを変更する必要があります。

origin  https://your-account@bitbucket.org/your-organization/example.git (fetch)
origin  https://your-account@bitbucket.org/your-organization/example.git (push)

その場合は下記コマンドで変更してください。

git remote set-url origin git@bitbucket.org:your-organization/example.git

bitbucket / github に接続する際に利用する鍵を指定する

現在の状態ではgithub/bitbucketに接続する際に、デフォルトの~/.ssh/id_rsaを利用してしまいます。
なので~/.ssh/configに設定を追加しましょう。
このファイルに追加することで接続先別に利用する鍵を設定することができます。

bitbucketの場合

~/.ssh/config
Host bitbucket.org
    HostName bitbucket.org
    User your-account
    IdentityFile ~/.ssh/other_id_rsa

githubの場合

~/.ssh/config
Host github.com
    HostName github.com
    User your-account
    IdentityFile ~/.ssh/other_id_rsa

秘密鍵のパスワードを毎回入力しないようにする

ここまでの設定で git clone などをすると、秘密鍵のパスワードの入力を求められてしまいます。
毎回これを入力するのは大変なのでssh-addを使ってパスワードをmacのキーチェーンに保存しましょう。

githubの提示する手順を参考にしています。

下記コマンドを実行します。

ssh-add -K ~/.ssh/other_id_rsa

するとpassphraseの入力を求められるので入力します。
以上でキーチェーンへの登録は完了です。
キーチェーンを開いて 「other_id_rsa」で検索してみると、登録されたデータが確認できます。

※はじめに記述されているssh-agentを立ち上げる下記コマンドはmacでは不要です。

eval "$(ssh-agent -s)" 

まとめ

以上で設定は終わりです。

macの場合はキーチェーンなどがあるので割と設定が簡単にできますね。

5
5
0

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
5
5