macOS SSH Key Auto-Configuration for Git
Prerequisites: Generate SSH Key Pair
-
Open Terminal
Use Spotlight (⌘+Space) to search for “Terminal” and open it. -
Generate Key Pair
Execute the following command (replace[email protected]with your email):Terminal window - When prompted, press Enter to use default settings.
- For extra security, you can set a passphrase.
-
Check Generated Files
Two files will be created in the~/.sshdirectory:Terminal window git_example # Private key (keep secure)git_example.pub # Public key (to be configured on Git server)
Configure Automatic Use of Specified Key
-
Edit SSH Config File
Terminal window mkdir -p ~/.ssh && chmod 700 ~/.sshvim ~/.ssh/config -
Add Configuration
Use the following template (modify parameters as needed):# Main Git service configurationHost git.example.comHostName git.example.comUser gitPort 22IdentityFile ~/.ssh/git_exampleIdentitiesOnly yes# Additional configuration (for other Git services)Host github.comHostName github.comUser gitIdentityFile ~/.ssh/github_key -
Set File Permissions
Terminal window chmod 600 ~/.ssh/config
Server-Side Configuration
- Add Public Key to Git Service
Copy the public key content:Add the public key to:Terminal window pbcopy < ~/.ssh/git_example.pub- GitHub: Settings → SSH and GPG keys
- GitLab: Preferences → SSH Keys
- Self-hosted Git service: Server’s
~/.ssh/authorized_keysfile
Verify Configuration
-
Test SSH Connection
Terminal window On success, you will see a welcome message from the service (e.g., GitHub’s “Hi username!”).
-
Test with Repository Clone
Terminal window The system will automatically use the specified key without manual intervention.
Troubleshooting
-
Debug Mode
Add the-vflag to see detailed connection process:Terminal window -
Common Issues
- Error
Permissions 0644 are too open: Runchmod 600 ~/.ssh/* - Connection timeout: Check firewall settings or network proxy configuration.
- Authentication failed: Confirm that the public key has been correctly added to the server.
- Error
Extended Use
By configuring multiple Host blocks, you can:
- Use different keys for different platforms (GitHub/GitLab/Gitee)
- Separate work and personal accounts
- Manage keys in multi-server environments
Note: The
git.example.comin this article is a placeholder. Replace it with your actual Git service address.