Last active
December 2, 2025 14:08
-
-
Save Keith-Hon/02f1ada47a65bbd71442f8126e54a689 to your computer and use it in GitHub Desktop.
Authenticate Github
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #### github ssh key #### | |
| #!/bin/bash | |
| # GitHub API URL | |
| GITHUB_API_URL="https://api.github.com" | |
| # GitHub Personal Access Token (replace with your token) | |
| GITHUB_TOKEN="$GITHUB_PERSONAL_TOKEN" | |
| # SSH Key Title (you can customize this) | |
| SSH_KEY_TITLE="$(hostname)-$(date +%Y-%m-%d)" | |
| # SSH Key File Path | |
| SSH_KEY_PATH="$HOME/.ssh/id_rsa" | |
| # Check if SSH key exists, if not generate one | |
| if [ ! -f "$SSH_KEY_PATH" ]; then | |
| echo "SSH key not found. Generating a new SSH key..." | |
| ssh-keygen -t rsa -b 4096 -C "$(whoami)@$(hostname)" -f "$SSH_KEY_PATH" -N "" | |
| echo "SSH key generated at $SSH_KEY_PATH" | |
| fi | |
| # Read the public key | |
| PUBLIC_KEY=$(cat "$SSH_KEY_PATH.pub") | |
| # Check if the public key is already added to GitHub | |
| KEY_EXISTS=$(curl -s -H "Authorization: token $GITHUB_TOKEN" "$GITHUB_API_URL/user/keys" | jq -r --arg title "$SSH_KEY_TITLE" '.[] | select(.title == $title) | .key') | |
| if [[ "$KEY_EXISTS" == "$PUBLIC_KEY" ]]; then | |
| echo "SSH key already exists on GitHub." | |
| exit 0 | |
| fi | |
| # Add the SSH key to GitHub | |
| echo "Adding SSH key to GitHub..." | |
| RESPONSE=$(curl -s -X POST -H "Authorization: token $GITHUB_TOKEN" -H "Content-Type: application/json" \ | |
| -d "{\"title\":\"$SSH_KEY_TITLE\",\"key\":\"$PUBLIC_KEY\"}" \ | |
| "$GITHUB_API_URL/user/keys") | |
| # Check if the key was added successfully | |
| if echo "$RESPONSE" | jq -e '.id' > /dev/null 2>&1; then | |
| echo "SSH key added successfully to GitHub." | |
| else | |
| echo "Failed to add SSH key to GitHub." | |
| echo "Response: $RESPONSE" | |
| exit 1 | |
| fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment