DEV Community

Cover image for I made a bash script to help automate adding new ssh keys
George Nance
George Nance

Posted on

I made a bash script to help automate adding new ssh keys

At my work, we have tons of ssh keys that we store in central repo. We have to move them to our .ssh folder so we can ssh into server. But you also need to set the permissions on the key file after you move it.

I started to get annoyed with having to set permissions every time so I created a bash file to automate this.

#!/bin/bash

# add_ssh_key - A script to move ssh key and set permissions

##### Constants

SSH_DIR=~/.ssh/


# Check for path
if [ -z "$1" ]; then
   echo "Please provide the path to the ssh key" 
   exit 1
fi

cp $1 $SSH_DIR
chmod 600 $SSH_DIR$(basename $1)
echo "Copied ${1} to .ssh dir and set permissions to 600"
Enter fullscreen mode Exit fullscreen mode

I also have a gist for it

Download and move that to whatever bin folder you have and run
chmod +x on the filename. For me, I made a bin folder at ~/bin but you can put it wherever you want.

Then add an alias to your .bashrc or whatever file your terminals sources. For me that is a file called .zshrc

alias add_ssh_key="~/bin/add_ssh_key.sh"
Enter fullscreen mode Exit fullscreen mode

Then open up a new terminal and you should be able to run:

add_ssh_key path/to/current/key
Enter fullscreen mode Exit fullscreen mode

And pretso! 🎉 You have a key with proper permissions.

Thanks for reading! Let me know any ssh automation you have set up.

Top comments (0)