Last active
May 15, 2023 20:04
-
-
Save domportera/084717c92c223a5a6cde7f603af34602 to your computer and use it in GitHub Desktop.
Generates an ssh key an automatically adds it to your bashrc
This file contains 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
#!/bin/bash | |
#----- CONFIG ----- | |
ssh_key_name=key_name | |
#if using with Unity, this should be left blank | |
password="" | |
# if using with unity, the host_alias should be substituted for the base remote URL in the package manager | |
host_alias="alias" | |
host="github.com" | |
ssh_path=C:/Windows/System32/OpenSSH | |
# true, false, append. | |
# true if you have never done this before | |
# append if you have and don't have your ssh-agent in the command. | |
# false if you're already set | |
overwrite_bashrc=true | |
bits=4096 | |
protocol=ed25519 | |
keygen_exec_path="$ssh_path/ssh-keygen.exe" | |
# Bash profile contents | |
bash_profile_contents="#!/bin/bash\nif [ -f ~/.bashrc ]\nthen\n~/.bashrc\nfi" | |
git config --global core.sshCommand "$ssh_path/ssh.exe" | |
#------ END CONFIG ----- | |
cd ~ #just in case bash is launched from elsewhere | |
if [ $(ps ax | grep [s]sh-agent | wc -l) -gt 0 ] ; then | |
echo "ssh-agent is already running" | |
else | |
eval "$(ssh-agent)" | |
# uncomment to prompt the user to generate a default SSH key | |
# if [ "$(ssh-add -l)" == "The agent has no identities." ] ; then | |
# ssh-add ~/.ssh/id_rsa | |
# fi | |
fi | |
if [ $overwrite_bashrc = true ] ; then | |
echo '#!/bin/bash' > .bashrc | |
echo 'eval $(ssh-agent -s)' > .bashrc | |
echo -e "$bash_profile_contents" > .bash_profile | |
elif [ $overwrite_bashrc = append ] ; then | |
echo 'eval $(ssh-agent -s)' >> .bashrc | |
fi | |
$keygen_exec_path -t $protocol -b $bits -N "$password" -f $ssh_key_name | |
existing_key=$(ssh-add -l | grep -q "$ssh_key_name") | |
if [ -z "$existing_key" ] ; then | |
ssh-add -d ~/$ssh_key_name | |
echo "key already added. Replacing" | |
fi | |
HOST_INFO="\nHost $host_alias\n Hostname $host\n AddKeysToAgent yes\n IdentityFile ~/$ssh_key_name" | |
#Example output: | |
#Host fc | |
# Hostname github.com | |
# AddKeysToAgent yes | |
# IdentityFile ~/key_name | |
CONFIG_FILE_PATH=$HOME/.ssh/config | |
touch "$CONFIG_FILE_PATH" | |
echo "Pausing for touch to finalize" | |
sleep 5s | |
if grep -q "$host_alias" "$CONFIG_FILE_PATH" ; then | |
echo "Host alias already exists - not overwriting. This may cause problems, consider a different alias or deleting the old one." | |
else | |
echo "Appending alias to $CONFIG_FILE_PATH" | |
echo -e "\n$HOST_INFO" >> "$CONFIG_FILE_PATH" | |
fi | |
echo "ssh-add ${ssh_key_name}" >> .bashrc | |
ssh-add $ssh_key_name |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment