Skip to content

Instantly share code, notes, and snippets.

@MParvin
Created November 19, 2022 15:47
Show Gist options
  • Save MParvin/2f86a0f7feaf3d5d93b4699d76d6cf17 to your computer and use it in GitHub Desktop.
Save MParvin/2f86a0f7feaf3d5d93b4699d76d6cf17 to your computer and use it in GitHub Desktop.
This script does is to add or remove the ssh keys of a github user to/from the authorized_keys file.
#!/bin/bash
add_ssh_keys(){
github_username=$1
IFS=$'
'
# Iterate over all keys in the github account
for key in $(curl -sSL github.com/$github_username.keys)
do
# Check if the key is already in the authorized_keys file
if ! grep -q "$key" ~/.ssh/authorized_keys
then
# If not, add it
echo "$key" >> ~/.ssh/authorized_keys
fi
done
}
remove_ssh_keys(){
github_username=$1
IFS=$'
'
# Iterate over all keys in the authorized_keys file
for key in $(curl -sSL github.com/$github_username.keys)
do
# add escape characters to the key
key=$(echo "$key" | sed 's/\//\\\//g')
# Check if the key is in the github account
if grep $key ~/.ssh/authorized_keys
then
# If it is, remove it
sed -i "/$key/d" ~/.ssh/authorized_keys
fi
done
}
# Usage: manage_ssh_keys.sh [add|remove] [github_username]
if [ $# -ne 2 ]; then
echo "Usage: $0 [add|remove] [github_username]"
exit 1
fi
if [ "$1" == "add" ]; then
add_ssh_keys $2
elif [ "$1" == "remove" ]; then
remove_ssh_keys $2
else
echo "Usage: $0 [add|remove] [github_username]"
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment