0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

SSHでgit cloneをする方法

Last updated at Posted at 2024-09-16

はじめに

こんにちは。ponponnsanです。最近遊びすぎると翌日に響くことが増えてきました。今年から考え始めたジムにそろそろ行く時がきたのか...

今回は、ssh接続でgit cloneする方法を紹介します。

経緯

githubのhttpsでのcloneが一般的ですが、社内サーバーだと個人アカウントでgit loginする必要があります。それだと他の人がcloneできないので、sshで接続してcloneさせようという試みです。

手順

  1. .ssh/configファイルを作成
  2. 公開鍵と秘密鍵を作成する
  3. githubに公開鍵を登録する
  4. ~/.ssh/configの設定をする
  5. sshでgit cloneする

それぞれの手順を追って見ていきましょう。

.ssh/configファイルを作成

最初に.ssh/configというファイルを作成していきます。
configはssh接続の設定を保存するファイルです。大体はホームディレクトリに.sshというファイルを作成し、その下にファイルを作成して行きます。

ファイルがある場合はこの手順を飛ばしても大丈夫です。
作成してあるかどうかは以下のコマンドで確認してください。

# configファイルがあるかどうかを確認
cat ~/.ssh/config

# .sshファイルを作成
mkdir -p ~/.ssh
chmod 700 ~/.ssh

mkdir -p ~/.ssh
mkdir: ディレクトリを作成するコマンド
-p: 親ディレクトリが存在しない場合は作成する
~/.ssh: ホームディレクトリ直下に.sshディレクトリを作成

chmod 700 ~/.ssh
chmod: ファイルやディレクトリの権限を変更するコマンド
700: 所有者にのみ読み取り、書き込み、実行の権限を与える

700のパーミッションの内訳を表で示します:

所有者 (User) グループ (Group) その他 (Others)
7 (rwx) 0 (---) 0 (---)

この表の詳細説明:

  • 所有者 (7):

    • r (読み取り): 4
    • w (書き込み): 2
    • x (実行): 1
    • 合計: 4 + 2 + 1 = 7
  • グループ (0):

    • すべての権限なし
  • その他 (0):

    • すべての権限なし

700のパーミッションでは、ファイルやディレクトリの所有者にのみフルアクセス権(読み取り、書き込み、実行)が与えられ、グループメンバーやその他のユーザーにはアクセス権が一切与えられません。このパーミッション設定は、セキュリティが重要な場合や、特定のユーザーのみがアクセスできるようにしたい場合に使用されます。

公開鍵と秘密鍵を作成する

ssh-keygen -t ed25519で鍵を生成します。
するとfile_nameは何にするか、パスワードは何にするか聞かれます。

  • ファイルの名前は混同しないように変えておくと便利
  • passphraseは空(Enter押すだけ)でもいい
ssh-keygen -t ed25519

Generating public/private rsa key pair.
Enter file in which to save the key (/home/username/.ssh/id_rsa): file_name
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 

ls -al ~/.sshでちゃんと~/.ssh配下にあることを確認します。

ls -al ~/.ssh

-rw------- 1 user user  411 May 12 15:09 file_name
-rw-r--r-- 1 user user   96 May 12 15:09 file_name.pub

githubに公開鍵を登録する

別リポジトリと同じデプロイキーは「Key is already in use」となり使えません。

登録したいリポジトリの Settings > Deploy keys > Add deploy key から
公開鍵file_name.pubを登録します。

スクリーンショット 2024-04-12 15.23.47.png

~/.ssh/configの設定をする

configファイルに鍵の設定をします。

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

デフォルトはgit@github.com:user/project.gitなのですが、
configのUser,Hostを変更を変えると、git cloneをするURLも変わります。

# デフォルト
git clone git@github.com:gituser/project.git

# configのUser,Hostを変更した場合
git clone [User]@[Host]:[リポジトリアドレス]

参考文献

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?