SSH com GitHub: Setup Completo e Seguro em 2025

January 15, 2025 (1y ago)

Fala dev! 👋

Se você ainda usa usuário e senha para fazer push no GitHub, está na hora de migrar para SSH! É mais seguro, prático e profissional.

Neste guia completo, vou te ensinar a configurar SSH com GitHub do zero, incluindo cenários avançados como múltiplas contas e troubleshooting.


🔐 Por que usar SSH?

Vantagens do SSH:

Diferença entre HTTPS e SSH:

# HTTPS (com senha/token)
git clone https://github.com/usuario/repo.git
 
# SSH (com chave)
git clone git@github.com:usuario/repo.git

🛠️ Setup inicial do SSH

Passo 1: Verificar se já tem SSH

# Verificar chaves existentes
ls -la ~/.ssh
 
# Se não existir a pasta, criar
mkdir -p ~/.ssh
chmod 700 ~/.ssh

Passo 2: Gerar nova chave SSH

# Gerar chave ED25519 (recomendada)
ssh-keygen -t ed25519 -C "seu-email@exemplo.com"
 
# Ou RSA (se ED25519 não for suportado)
ssh-keygen -t rsa -b 4096 -C "seu-email@exemplo.com"

Durante a geração:

Passo 3: Adicionar chave ao SSH agent

# Iniciar o SSH agent
eval "$(ssh-agent -s)"
 
# Adicionar chave privada
ssh-add ~/.ssh/id_ed25519
 
# Verificar chaves adicionadas
ssh-add -l

Passo 4: Adicionar chave pública ao GitHub

# Copiar chave pública para clipboard
cat ~/.ssh/id_ed25519.pub | pbcopy
 
# Ou no Linux
cat ~/.ssh/id_ed25519.pub | xclip -selection clipboard

No GitHub:

  1. Vá em SettingsSSH and GPG keys
  2. Clique em New SSH key
  3. Cole a chave pública
  4. Dê um nome descritivo (ex: "MacBook Pro - 2025")
  5. Clique em Add SSH key

🧪 Testando a conexão

# Testar conexão SSH
ssh -T git@github.com
 
# Resposta esperada:
# Hi username! You've successfully authenticated, but GitHub does not provide shell access.

Se der erro, verifique:

# Debug detalhado
ssh -vT git@github.com
 
# Verificar configuração
ssh -F ~/.ssh/config git@github.com

🔧 Configuração avançada

1. Múltiplas contas GitHub

Crie arquivo de configuração:

# ~/.ssh/config
# Conta pessoal
Host github.com
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_ed25519_personal
 
# Conta trabalho
Host github-work
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_ed25519_work

Gerar chaves separadas:

# Chave pessoal
ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519_personal -C "pessoal@email.com"
 
# Chave trabalho
ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519_work -C "trabalho@empresa.com"

Usar contas diferentes:

# Repositório pessoal
git clone git@github.com:usuario-pessoal/repo.git
 
# Repositório trabalho
git clone git@github-work:usuario-trabalho/repo.git

2. Configuração global do Git

# Configurar usuário global
git config --global user.name "Seu Nome"
git config --global user.email "seu-email@exemplo.com"
 
# Configurar editor
git config --global core.editor "code --wait"
 
# Configurar branch padrão
git config --global init.defaultBranch main
 
# Verificar configurações
git config --list

3. SSH Agent automático

macOS (usando Keychain):

# Adicionar ao ~/.ssh/config
Host *
    AddKeysToAgent yes
    UseKeychain yes
    IdentityFile ~/.ssh/id_ed25519

Linux (usando systemd):

# Habilitar SSH agent
systemctl --user enable ssh-agent
systemctl --user start ssh-agent

🚀 Workflows práticos

1. Clonar repositório existente

# Com HTTPS (migrar para SSH)
git clone https://github.com/usuario/repo.git
cd repo
 
# Alterar remote para SSH
git remote set-url origin git@github.com:usuario/repo.git
 
# Verificar
git remote -v

2. Criar repositório novo

# Criar pasta do projeto
mkdir meu-projeto
cd meu-projeto
 
# Inicializar Git
git init
 
# Adicionar arquivos
echo "# Meu Projeto" > README.md
git add .
 
# Primeiro commit
git commit -m "Initial commit"
 
# Adicionar remote SSH
git remote add origin git@github.com:usuario/meu-projeto.git
 
# Push inicial
git branch -M main
git push -u origin main

3. Trabalhando com branches

# Criar e trocar para nova branch
git checkout -b feature/nova-funcionalidade
 
# Fazer alterações e commit
git add .
git commit -m "feat: adiciona nova funcionalidade"
 
# Push da branch
git push -u origin feature/nova-funcionalidade
 
# Criar Pull Request no GitHub

🔍 Troubleshooting comum

1. Erro: Permission denied (publickey)

# Verificar se a chave está no agent
ssh-add -l
 
# Se não estiver, adicionar
ssh-add ~/.ssh/id_ed25519
 
# Verificar permissões
chmod 600 ~/.ssh/id_ed25519
chmod 644 ~/.ssh/id_ed25519.pub

2. Erro: Host key verification failed

# Limpar known_hosts
ssh-keygen -R github.com
 
# Ou adicionar manualmente
ssh-keyscan -t rsa github.com >> ~/.ssh/known_hosts

3. Chave não reconhecida pelo GitHub

# Verificar se a chave pública está correta
cat ~/.ssh/id_ed25519.pub
 
# Comparar com a chave no GitHub
# Settings → SSH and GPG keys

4. Múltiplas chaves não funcionam

# Debug com chave específica
ssh -i ~/.ssh/id_ed25519_personal -T git@github.com
 
# Verificar configuração
ssh -F ~/.ssh/config -T git@github.com

🛡️ Segurança e boas práticas

1. Proteção da chave privada

# Permissões corretas
chmod 700 ~/.ssh
chmod 600 ~/.ssh/id_ed25519
chmod 644 ~/.ssh/id_ed25519.pub
 
# Backup seguro (criptografado)
tar -czf ssh-keys-backup.tar.gz ~/.ssh
gpg -c ssh-keys-backup.tar.gz

2. Rotação de chaves

# Gerar nova chave
ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519_new -C "novo-email@exemplo.com"
 
# Adicionar ao GitHub
cat ~/.ssh/id_ed25519_new.pub | pbcopy
 
# Testar nova chave
ssh -i ~/.ssh/id_ed25519_new -T git@github.com
 
# Remover chave antiga do GitHub
# (fazer via interface web)

3. Monitoramento de acesso

# Verificar logs de SSH
tail -f /var/log/auth.log
 
# GitHub mostra último uso das chaves
# Settings → SSH and GPG keys

🔧 Scripts úteis

1. Script de setup automático

#!/bin/bash
# setup-ssh-github.sh
 
echo "🔑 Configurando SSH para GitHub..."
 
# Gerar chave
read -p "Digite seu email: " email
ssh-keygen -t ed25519 -C "$email"
 
# Adicionar ao agent
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519
 
# Mostrar chave pública
echo "📋 Sua chave pública:"
cat ~/.ssh/id_ed25519.pub
echo ""
echo "✅ Copie a chave acima e adicione no GitHub:"
echo "https://github.com/settings/ssh/new"

2. Script de teste de conexão

#!/bin/bash
# test-ssh-github.sh
 
echo "🧪 Testando conexão SSH com GitHub..."
 
if ssh -T git@github.com 2>&1 | grep -q "successfully authenticated"; then
    echo "✅ SSH configurado corretamente!"
else
    echo "❌ Erro na configuração SSH"
    echo "🔍 Debug:"
    ssh -vT git@github.com
fi

📱 Configuração em diferentes SOs

Windows (WSL/Git Bash)

# Usar o mesmo processo do Linux
# Mas verificar se o SSH agent está rodando
eval "$(ssh-agent -s)"

Windows (PowerShell)

# Iniciar SSH agent
Start-Service ssh-agent
 
# Adicionar chave
ssh-add ~/.ssh/id_ed25519

macOS

# Usar Keychain (recomendado)
ssh-add --apple-use-keychain ~/.ssh/id_ed25519

✅ Checklist de configuração


🎯 Conclusão

SSH com GitHub é essencial para qualquer desenvolvedor profissional. É mais seguro, rápido e elimina a necessidade de senhas.

Principais benefícios:

Próximos passos:

  1. Configure SSH hoje mesmo
  2. Migre repositórios existentes
  3. Configure múltiplas contas se necessário
  4. Automatize com scripts

Quer ajuda com alguma configuração específica? Me chama no GitHub! 🚀

Allisson Lima
Desenvolvedor Frontend | Especialista em DevOps e Git