How I Stopped Accidentally Pushing to the Wrong GitHub Account
I remember the night vividly. I was working on a personal side project, excited to push some changes to GitHub. After a long coding…
How I Stopped Accidentally Pushing to the Wrong GitHub Account

I remember the night vividly. I was working on a personal side project, excited to push some changes to GitHub. After a long coding session, I typed git push... and froze — I had accidentally pushed my personal code to my work repository. My manager would not have been pleased.
In that moment of panic, I realized: I needed a better way to manage multiple GitHub accounts — one for personal projects, one for work. No more password prompts. No more accidental commits. No more chaos.
This guide will help you manage multiple GitHub accounts safely and push to the correct account every time on both Mac and Windows.
Step 0: Define Your Accounts
Before diving into commands, clarify your accounts. For example:
Personal GitHub Account
- Username: SampleUserPersonal
- Email: sample.personal@gmail.com
- Purpose: Side projects, tutorials, experiments
- SSH Key Name: id_ed25519_personal
Work GitHub Account
- Username: SampleUserWork
- Email: sample.work@company.com
- Purpose: Professional projects
- SSH Key Name: id_ed25519_work
Why this matters: Separating identities prevents mistakes, keeps your commit history clean, and ensures Git uses the correct credentials.
Step 1: Generate SSH Keys
Each account needs a unique SSH key. Think of them as project-specific digital fingerprints.
MacOS & Linux:
# Personal
ssh-keygen -t ed25519 -C "sample.personal@gmail.com" -f ~/.ssh/id_ed25519_personal
# Work
ssh-keygen -t ed25519 -C "sample.work@company.com" -f ~/.ssh/id_ed25519_work
Windows (PowerShell):
# Personal
ssh-keygen -t ed25519 -C "sample.personal@gmail.com" -f C:\Users\SampleUser\.ssh\id_ed25519_personal
# Work
ssh-keygen -t ed25519 -C "sample.work@company.com" -f C:\Users\SampleUser\.ssh\id_ed25519_work
💡 Tip: Press Enter to accept the default location. Leaving the passphrase empty is convenient, but adding one increases security.
Step 2: Add Public Keys to GitHub
Every SSH key has a public half you must add to GitHub. This is how GitHub verifies your identity.
View public keys:
MacOS & Linux:
cat ~/.ssh/id_ed25519_personal.pub
cat ~/.ssh/id_ed25519_work.pub
Windows (PowerShell):
Get-Content C:\Users\SampleUser\.ssh\id_ed25519_personal.pub
Get-Content C:\Users\SampleUser\.ssh\id_ed25519_work.pub
Copy each key and paste it into the SSH and GPG keys section of the corresponding GitHub account.
Step 3: Configure SSH for Multiple Accounts
Create an SSH config file to tell Git which key to use for which repository.
Open the SSH config file:
- MacOS / Linux:
nano ~/.ssh/config
- Windows (PowerShell):
code $env:USERPROFILE\.ssh\config
Add the following entries:
# Personal GitHub account
Host github-personal
HostName github.com
User git
IdentityFile ~/.ssh/id_ed25519_personal
IdentitiesOnly yes
# Work GitHub account
Host github-work
HostName github.com
User git
IdentityFile ~/.ssh/id_ed25519_work
IdentitiesOnly yes
✅ Why this matters: Using aliases like github-personal or github-work ensures Git automatically uses the correct SSH key.
Step 4: Clone Repositories Using the Correct Identity
Use your new aliases instead of the default GitHub URL:
Personal Repo:
git clone git@github-personal:SampleUserPersonal/sample-personal-repo.git
Work Repo:
git clone git@github-work:SampleUserWork/sample-work-repo.git
Step 5: Set Git Identity Per Project
Even with the right SSH key, Git needs the correct username and email for commits.
Inside your cloned personal repo:
git config user.name "SampleUserPersonal"
git config user.email "sample.personal@gmail.com"
Inside your cloned work repo:
git config user.name "SampleUserWork"
git config user.email "sample.work@company.com"
⚠️ Reminder: If you forget this step, commits may be attributed to the wrong account.
Step 6: Test the Setup
Navigate to a repository and try a push:
git push origin main
Expected result:
- No username/password prompts
- Git automatically uses the correct SSH key
- Commit is correctly attributed to the right account
You can also test the SSH connection:
ssh -T git@github-personal
ssh -T git@github-work
Step 7: Working with Personal and Work Repositories
Once your SSH keys and config aliases are set up, you don’t need to manually switch GitHub accounts. Git automatically picks the right identity based on the repository you’re working in.
- For personal projects, always use the alias
github-personalin your remote URL:
git@github-personal:YourPersonalUsername/repo.git
- For work projects, always use the alias
github-work:
git@github-work:YourWorkUsername/repo.git
Check Which Remote Your Repository Uses
Inside your repository, run:
git remote -v
You’ll see something like this:
origin git@github-personal:SampleUserPersonal/sample-repo.git (fetch)
origin git@github-personal:SampleUserPersonal/sample-repo.git (push)
This tells you which alias (and therefore which GitHub account) your repository is connected to. If it’s correct, you’re ready to work safely without accidentally pushing to the wrong account.
Step 8: Creating New Projects
Use the correct alias from the start:
Personal Example:
echo "# sample-tutorials" >> README.md
git init
git add README.md
git commit -m "first commit"
git branch -M main
git remote add origin git@github-personal:SampleUserPersonal/sample-tutorials.git
git push -u origin main
Work Example:
echo "# sample-tutorials" >> README.md
git init
git add README.md
git commit -m "first commit"
git branch -M main
git remote add origin git@github-work:SampleUserWork/sample-tutorials.git
git push -u origin main
Step 9: Automate with Python Script
This Python script automates key generation, updates SSH config, and prints public keys.
#!/usr/bin/env python3
"""
Automated GitHub SSH Setup Script (Cross-platform Python)
---------------------------------------------------------
- Creates SSH keys for personal and work GitHub accounts
- Updates ~/.ssh/config safely (adds host aliases)
- Displays public keys to copy into GitHub
- Windows-friendly checks with clear messages
"""
import os
import shutil
import subprocess
import datetime
import sys
import shutil as sh
# --- CONFIGURATION: Test/Dummy accounts ---
PERSONAL_EMAIL = "personal@example.com"
PERSONAL_USERNAME = "TestPersonal"
WORK_EMAIL = "work@example.com"
WORK_USERNAME = "TestWork"
# SSH key paths (Windows compatible)
HOME = os.path.expanduser("~") or os.environ.get("USERPROFILE")
PERSONAL_KEY = os.path.join(HOME, ".ssh", "id_ed25519_personal")
WORK_KEY = os.path.join(HOME, ".ssh", "id_ed25519_work")
# ---------------- Windows / Dependency Checkers ----------------
def check_python():
if sys.version_info < (3, 8):
print(f"ERROR: Python 3.8+ required, you have {sys.version.split()[0]}")
sys.exit(1)
def check_ssh_keygen():
"""Ensure ssh-keygen is available."""
if sh.which("ssh-keygen") is None:
print("ERROR: ssh-keygen not found.")
if sys.platform.startswith("win"):
print("Hint: On Windows, install Git for Windows or enable OpenSSH Client in Settings → Apps → Optional Features")
else:
print("Hint: Install OpenSSH tools via your package manager.")
sys.exit(1)
def check_ssh_agent():
"""Check if ssh-agent is running (optional)."""
try:
result = subprocess.run(["ssh-add", "-l"], capture_output=True, text=True)
if "The agent has no identities" in result.stdout:
print("INFO: SSH agent is running but no keys loaded. You may need to run 'ssh-add <key>' manually.")
except FileNotFoundError:
print("INFO: ssh-agent not found. Keys may need to be manually added.")
def check_home_dir():
"""Ensure HOME directory exists."""
if not HOME or not os.path.exists(HOME):
print(f"ERROR: Cannot find home directory: {HOME}")
if sys.platform.startswith("win"):
print("Make sure USERPROFILE environment variable is set.")
sys.exit(1)
return HOME
def check_ssh_folder(ssh_folder):
"""Ensure ~/.ssh folder exists and is writable."""
if not os.path.exists(ssh_folder):
try:
os.makedirs(ssh_folder, exist_ok=True)
print(f"Created SSH folder: {ssh_folder}")
except PermissionError:
print(f"ERROR: Cannot create SSH folder at {ssh_folder}")
print("Check folder permissions or run as a user with access.")
sys.exit(1)
# ---------------- Core Functions ----------------
def run_command(cmd):
"""Run a shell command safely and exit on failure."""
try:
subprocess.run(cmd, check=True)
except subprocess.CalledProcessError as e:
print(f"ERROR: Command failed: {' '.join(cmd)}\n{e}")
sys.exit(1)
def backup_ssh_folder(ssh_folder):
"""Backup existing ~/.ssh folder, keeping only one backup."""
backup_path = f"{ssh_folder}-backup-latest"
if os.path.exists(ssh_folder):
# Remove previous latest backup if it exists
if os.path.exists(backup_path):
shutil.rmtree(backup_path)
shutil.copytree(ssh_folder, backup_path)
print(f"Backup complete: {backup_path}")
else:
print("No existing SSH folder found. Creating new...")
os.makedirs(ssh_folder, exist_ok=True)
def generate_key(key_path, email):
"""Generate an SSH key if missing."""
if not os.path.exists(key_path):
run_command(["ssh-keygen", "-t", "ed25519", "-C", email, "-f", key_path, "-N", ""])
print(f"SSH key created: {key_path}")
else:
print(f"SSH key already exists: {key_path}")
def update_ssh_config(config_path, host_alias, key_path):
"""Add SSH config entry if missing."""
entry = (
f"\n# {host_alias} GitHub account\n"
f"Host github-{host_alias}\n"
f" HostName github.com\n"
f" User git\n"
f" IdentityFile {key_path}\n"
f" IdentitiesOnly yes\n"
)
if os.path.exists(config_path):
with open(config_path, "r", encoding="utf-8") as f:
content = f.read()
if f"Host github-{host_alias}" in content:
print(f"SSH config already has github-{host_alias}")
return
backup = f"{config_path}.backup_{datetime.datetime.now().strftime('%Y%m%d%H%M%S')}"
shutil.copy2(config_path, backup)
print(f"Existing SSH config backed up: {backup}")
else:
open(config_path, "a").close()
with open(config_path, "a", encoding="utf-8") as f:
f.write(entry)
print(f"Added github-{host_alias} entry to SSH config")
def show_public_key(key_path, label):
"""Print the public key for GitHub."""
pub_file = key_path + ".pub"
if os.path.exists(pub_file):
with open(pub_file, "r", encoding="utf-8") as f:
print(f"\n{label} Public Key:\n{f.read().strip()}")
print("Add it here: https://github.com/settings/keys\n")
else:
print(f"Public key not found: {pub_file}")
# ---------------- Main Workflow ----------------
def main():
ssh_folder = os.path.join(HOME, ".ssh")
config_file = os.path.join(ssh_folder, "config")
print("=== Automated GitHub SSH Setup ===")
# Step 0: Dependency checks
check_python()
check_ssh_keygen()
check_home_dir()
check_ssh_folder(ssh_folder)
check_ssh_agent()
# Step 1: Backup ~/.ssh
backup_ssh_folder(ssh_folder)
# Step 2: Generate keys
print("\nGenerating SSH keys (if missing)...")
generate_key(PERSONAL_KEY, PERSONAL_EMAIL)
generate_key(WORK_KEY, WORK_EMAIL)
# Step 3: Update SSH config
print("\nUpdating SSH config...")
update_ssh_config(config_file, "personal", PERSONAL_KEY)
update_ssh_config(config_file, "work", WORK_KEY)
# Step 4: Show public keys
print("\nPublic keys (copy these into GitHub):")
show_public_key(PERSONAL_KEY, "Personal")
show_public_key(WORK_KEY, "Work")
# Step 5: Git identity instructions
print("\nGit identity setup per repo:")
print(f"Personal repos:\n git config user.name \"{PERSONAL_USERNAME}\"\n git config user.email \"{PERSONAL_EMAIL}\"\n")
print(f"Work repos:\n git config user.name \"{WORK_USERNAME}\"\n git config user.email \"{WORK_EMAIL}\"\n")
# Step 6: Clone instructions
print("\nExample clone commands:")
print("Personal repo: git clone git@github-personal:<username>/<repo>.git")
print("Work repo: git clone git@github-work:<username>/<repo>.git")
# Step 7: Test instructions
print("\nTest your SSH setup:")
print("ssh -T git@github-personal")
print("ssh -T git@github-work")
print("\nSetup complete! SSH keys ready and config updated.")
if __name__ == "__main__":
main()
Instructions:
- Make sure Python 3.8+ is installed.
- Save the script and run:
python setup_github_ssh.py
- Copy the printed public keys into GitHub manually.
Summary
- Separate accounts prevent accidental pushes.
- SSH keys and config aliases automate identity selection.
- Git username/email per repo ensures proper commit attribution.
- Python script saves time and reduces human error.
Your Git workflow is now seamless, safe, and fully automated for multiple GitHub accounts.
메타데이터
- post_id
- fbe30e50490c
- slug
- how-i-stopped-accidentally-pushing-to-the-wrong-github-account-fbe30e50490c
- url
- https://medium.com/@officialmukeshdevrath/how-i-stopped-accidentally-pushing-to-the-wrong-github-account-fbe30e50490c
- canonical_url
- https://medium.com/@officialmukeshdevrath/how-i-stopped-accidentally-pushing-to-the-wrong-github-account-fbe30e50490c
- author_url
- https://medium.com/@officialmukeshdevrath
- status
- ok
- fetched_at
- 2026-06-13 16:00:06