0
1

Gitをhttpsからsshに接続変更する

Posted at

概要

Gitを最初はhttpsでcloneした人向け。sshに接続変更する。

状態の確認

ターミナルからGitリポジトリをcloneしたところで以下を入力

コマンド
git remote -v

多分httpsでやってるとこうなる。

実行結果例
origin  https://github.com/example/hogehoge.git (fetch)
origin  https://github.com/example/hogehoge.git (push)

sshの鍵作成

コマンド
ssh-keygen -t rsa -b 4096 -C "自身のメールアドレス"

上記入力後、鍵の名前、パスワード、パスワード(確認)を入力する。
(ここでは
鍵の名前: git_rsa
パスワード: 自分自身のPCパスワードにする)

% ssh-keygen -t rsa -b 4096 -C "test@example.com"
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/****/.ssh/id_rsa): git_rsa
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in git_rsa
Your public key has been saved in git_rsa.pub

秘密鍵: git_rsa
公開鍵: git_rsa.pub

が作成される。

※-Cオプションの備考

ssh-keygenコマンドの-Cはコメントのオプションです。コメントは、公開鍵の末尾に付与されます。
オプションを使用しなかった場合は、ssh-keygenを実行した環境のユーザー名とホスト名で username@hostname が付与されます。
ここでは業務で鍵を作る場合に誰が作ったか一意で見分けやすいという理由から、"自身のメールアドレス"という具合にさせていただきました。

公開鍵をGitHubに登録

New SSH keyを押す

スクリーンショット 2024-06-12 9.53.08.png

この入力画面になる。

スクリーンショット 2024-06-12 9.54.11.png

以下を入力する。

Title: GitSSH
Key type: Authentication Key
Key: さっきのgit_rsa.pubの中身コピペ

Add SSH keyで公開鍵を登録。

sshのclone 先の設定

(私のGitHub画面で恐縮ですが)
cloneしたいリポジトリのここを押してコピーします。

スクリーンショット 2024-06-12 9.38.10.png

URL変更

ターミナルで以下のコマンドを実行して先ほどコピーしたsshのURLにします。

コマンド
git remote set-url origin git@github.com:hogehoge/fugafuga.git

GitHubのssh configを設定する

ターミナルで以下のコマンドを実行。

コマンド
vi ~/.ssh/config

以下を追記

.ssh/configの中身
Host github github.com
        HostName github.com
        IdentityFile ここgit_rsaの設置場所
        User git

状態の確認

ターミナルからGitリポジトリをcloneしたところで以下を入力

git remote -v

こうなる。

origin	git@github.com:hogehoge/fugafuga.git (fetch)
origin	git@github.com:hogehoge/fugafuga.git (push)

秘密鍵の権限変更

ターミナルで以下のコマンドを実行。

コマンド
chmod 600 git_rsaのファイル自体を指定

※git_rsaが秘密鍵ファイルなので、所有者のみの実行権限じゃないと警告が出るのでそのファイル自体の権限を変えてねってことです

接続テスト

ターミナルで以下のコマンドを実行。

コマンド
ssh -T git@github.com
Hi ****! You've successfully authenticated, but GitHub does not provide shell access.

がでればOK

0
1
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
0
1