GitHub – SSH 방식 연결 방법


1. SSH란?


2. SSH 키 생성

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

생성 결과:

→ 기존 키가 있다면 -f ~/.ssh/파일명 옵션으로 이름을 바꿔 생성


3. SSH 공개키 GitHub에 등록

  1. 공개키 복사:
cat ~/.ssh/id_rsa.pub
  1. GitHub 접속
    Settings > SSH and GPG Keys > New SSH Key
  2. 제목 입력 후 키 붙여넣기 → 저장

4. SSH 연결 테스트

ssh -T git@github.com
Hi username! You've successfully authenticated, but GitHub does not provide shell access.

5. 원격 저장소 SSH 주소로 연결

git remote add origin git@github.com:username/repository.git
git remote set-url origin git@github.com:username/repository.git

6. Git 기본 작업 흐름 (SSH 사용 시)

git pull origin main
git add .
git commit -m "커밋 메시지"
git push origin main

7. SSH 키를 여러 개 사용하는 방법

7.1 SSH 키 여러 개 생성

ssh-keygen -t rsa -C "email1@example.com" -f ~/.ssh/id_rsa_personal
ssh-keygen -t rsa -C "email2@example.com" -f ~/.ssh/id_rsa_work

7.2 ~/.ssh/config 설정

Host github.com-personal
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_rsa_personal

Host github.com-work
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_rsa_work

7.3 저장소 원격 주소 설정

git remote set-url origin git@github.com-work:username/repo.git

7.4 연결 테스트

ssh -T github.com-work

✅ 보안 팁


8. GitHub에 SSH 키 자동으로 추가하는 스크립트

8.1 필요 조건


8.2 스크립트 예시

#!/bin/bash

# 설정: 사용자 정보 입력
GITHUB_USERNAME="your-username"
GITHUB_TOKEN="your-personal-access-token"
SSH_KEY_TITLE="My Laptop SSH Key"
SSH_KEY_PATH="$HOME/.ssh/id_rsa.pub"

# 공개키 가져오기
PUB_KEY=$(cat $SSH_KEY_PATH)

# GitHub API로 키 등록
curl -u "$GITHUB_USERNAME:$GITHUB_TOKEN" \
  --data "{\"title\":\"$SSH_KEY_TITLE\",\"key\":\"$PUB_KEY\"}" \
  https://api.github.com/user/keys

8.3 사용 방법

  1. 위 스크립트를 add_ssh_key.sh로 저장
  2. 실행 권한 부여:
chmod +x add_ssh_key.sh
  1. 실행:
./add_ssh_key.sh

✅ 실행되면 GitHub 계정에 SSH 키가 자동 등록됨


9. SSH 키 백업 및 복구 방법

9.1 백업 방법

mkdir -p ~/backup_ssh_keys
cp ~/.ssh/id_rsa* ~/backup_ssh_keys/

9.2 복구 방법

  1. 복사한 키 파일을 다시 ~/.ssh 디렉토리에 복원
cp ~/backup_ssh_keys/id_rsa* ~/.ssh/
chmod 600 ~/.ssh/id_rsa
chmod 644 ~/.ssh/id_rsa.pub
  1. 퍼미션 문제 방지:
    • id_rsa: 600 (읽기/쓰기)
    • id_rsa.pub: 644 (읽기 가능)

9.3 권한 오류 방지

chmod 700 ~/.ssh
chmod 600 ~/.ssh/id_rsa
chmod 644 ~/.ssh/id_rsa.pub

✅ 팁






Revision #2
Created 20 May 2025 23:50:04 by Dain
Updated 20 May 2025 23:52:12 by Dain