LoginSignup
1

More than 3 years have passed since last update.

特定用途の公開鍵を作成して使う SSH Keys

Last updated at Posted at 2019-05-05

既存の鍵ファイルがある状態でGithub用の公開鍵を作る際
既存ファイル(id_rsa id_rsa.pub)と分けて管理したかったので、その際の作成作業メモ

既に鍵認証ファイルを作成している前提で進めます

移動
cd ~/.ssh
ll

鍵ファイルの作成

↓ コメントは作成する.pubファイル内に記載されます。

作成
# ssh-keygen -C コメント -f 鍵ファイルの名称
ssh-keygen -C for_github_key -f github_key

passphrase入力はご自由に

確認
ls | grep github_key
作成した鍵ファイル
github_key
github_key.pub

githubに公開鍵ファイル(github_key.pub)を登録する (※下記項に記載)

あとは、sshアクセス時にファイル指定して利用したり

ssh
ssh -i ~/.ssh/github_key user@example.com

~/.ssh/configで指定すれば、特定アクセス時に固定ファイル使用でアクセスできる

~/.ssh/config
・

Host github
  HostName github.com
  IdentityFile ~/.ssh/github_key

Githubに公開鍵を登録する

公開鍵ファイルの内容を表示
cat ~/.ssh/github_key.pub

Githubの個人アカウント内で公開鍵ファイルの登録をする
https://github.com/settings/ssh/new

titleには管理しやすいようにファイル名とかを適当に入力

登録できたらコンソールからsshでアクセスできるか試す
sshコマンドでは先ほど作成した秘密鍵を指定してアクセスする

sshアクセス確認
ssh -Ti ~/.ssh/github_key git@github.com
アクセス成功時のメッセージ
Hi Tough_guy! You've successfully authenticated, but GitHub does not provide shell access.

git( push)コマンドを利用できるように、.ssh/config.gitconfigに追記する

/.ssh/configの末尾に追記
echo "\nHost github\n    HostName github.com\n    IdentityFile ~/.ssh/github_key\n    User git" >> ~/.ssh/config
.gitconfigの末尾に追記
echo "[url \"github:\"]\n   InsteadOf = https://github.com/\n   InsteadOf = git@github.com:" >> ~/.gitconfig
~/.ssh/config
・
・
・

Host github
    HostName github.com
    IdentityFile ~/.ssh/github_key
    User git
~/.gitconfig
[user]
.
.
.
[url "github:"]
   InsteadOf = https://github.com/
   InsteadOf = git@github.com:

コンソールからsshアクセスして、successfully authenticatedメッセージが表示されれば設定成功

sshアクセス確認
ssh -T git@github.com

上記が失敗する場合、ssh-agentに秘密鍵を登録してから再度試してみる

ssh-add ~/.ssh/github_key

# 確認
ssh-add -l 

まだリポジトリを作成してなければ、Githubで作成しとく
https://github.com/new

ここまでやれば、登録した鍵ファイルを利用した接続でgit pushが実行できるようになってるはず

参考

GitHubでssh接続する手順~公開鍵・秘密鍵の生成から~ - Qiita
Wokashi: サーバに新たなSSH公開鍵を追加する
ssh-agentの使い方 - Qiita
Githubからリポジトリをcloneする | ひまりさんの技術日記
git clone 時に秘密鍵を指定する - Qiita
Git における SSH オプション指定方法あれこれ - Qiita
【Github】ローカルからリモートリポジトリのへプッシュ - Qiita
ssh - UNIX/Linuxコマンド - IT専科

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
1