GitHubにSSH接続する方法

秘密鍵の生成と、公開鍵の設置

eyecatch github

1. GitHub用のSSHキーを生成する

昔はRSAでSSHキーを生成していたようですが、RSAより強固らしいed25519でSSHキーを生成します。

-cオプションを使って、コメントにメールアドレスを付与します。

$ cd ~/.ssh
$ ssh-keygen -t ed25519 -C "your_email@example.com"

SSHキーの保存場所を聞かれるので、~/.ssh下に設置します。

Generating public/private ed25519 key pair.
Enter file in which to save the key (/home/username/.ssh/id_ed25519): /home/username/.ssh/id_ed25519

パスフレーズを設定する場合は、入力します。

Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 

これで、SSHキーの作成が完了です。

$ ls ~/.ssh
id_ed25519  id_ed25519.pub  known_hosts

2. SSHキーをssh-agentに追加する

パスフレーズを聞かれないようにするため、ssh-agentに秘密鍵を追加します。

2.1. ssh-agentを起動する

ssh-agentを実行します。

% eval "$(ssh-agent -s)"

2.2. configファイルを更新する

~/.ssh/configファイルを作成して、修正します。

$ touch ~/.ssh/config
$ chmod 600 ~/.ssh/config
$ vim config

configファイルに追記します。

Host github
    HostName github.com
    IdentityFile ~/.ssh/id_ed25519
    TCPKeepAlive yes
    IdentitiesOnly yes
    User git

2.3. ssh-agentに鍵を登録する

ssh-add -K ~/.ssh/id_ed25519

3. SSHキーをGitHubアカウントに追加する

GitHubにログインし、https://github.com/settings/keysから、New SSH keyボタンをクリックします。

GitHub New SSH key button

Titleにマシーン名、Keyに先ほど作成した、id_ed25519.pubの中身をコピペし、Add SSH keyボタンをクリックします。

GitHub SSH keys Add new

パスワード入力が必要な場合は、入力します。SSH keysの中に、追加したSSH keyが表示されれば完了です。

4. SSH接続をテストする

sshで接続テストします。ユーザ名は、configで設定済みなので、githubと打つだけで十分です。

$ ssh -T github

出力メッセージに

Hi username! You've successfully authenticated, but GitHub does not provide shell access.

と、出てば接続できています。

See Also

ssh-keygen

SSH接続用の秘密鍵・公開鍵の作成

Nushell

Rust製シェル

2024/04/15

今日見つけたツール

DuckDB

SQLiteライクな軽量DB