Skip to content

Instantly share code, notes, and snippets.

@robmsmt
Last active April 11, 2024 04:47
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save robmsmt/b8300e7a0d711a7616e948a8232289a5 to your computer and use it in GitHub Desktop.
Save robmsmt/b8300e7a0d711a7616e948a8232289a5 to your computer and use it in GitHub Desktop.
make_user_gen_ssh.sh
#!/bin/bash
NEW_USER=$1
set -e
if [ -z "$NEW_USER" ];then
echo "Please provide user as arg... exiting."
exit 1
fi
sudo adduser $NEW_USER
mkdir -p user_keys
ssh-keygen -f user_keys/$NEW_USER
sudo -u $NEW_USER mkdir -p /home/$NEW_USER/.ssh/
sudo cp user_keys/$NEW_USER* /home/$NEW_USER/.ssh/
sudo chown -R $NEW_USER /home/$NEW_USER/.ssh
sudo su $NEW_USER <<'EOF'
cd ~/.ssh
cat *.pub >> ./authorized_keys
EOF
chmod 600 user_keys/$NEW_USER*
zip -re user_keys/$NEW_USER.zip user_keys/$NEW_USER user_keys/$NEW_USER.pub
echo "User setup complete... send them private+pub key:"
echo "$(readlink -f user_keys/$NEW_USER.zip)"
~
@gitcoleman
Copy link

Hi,

Just a quick question, would this script not create a ssh-key for the current logged in user and not for the newly created user?
"ssh-keygen -f user_keys/$NEW_USER" would create a private and public keys for the logged in user and just name the files with the newly created username. If you "su" to the new user first and then run the ssh-keygen command, that should create a key pair for the new user.

Please correct me if i'm wrong.

@robmsmt
Copy link
Author

robmsmt commented Oct 5, 2021

Hi,

No it generates the keys and cp them into the new users directory /home/$NEW_USER/.ssh/ . Then adds their public key to ~/.ssh/authorized_keys. In general it might be better to let the user generate their own keys they send you the public key which you add to authorized_keys. This way you never have a copy of their priv key. For me, at the time, this was more automated/easier route.

If you "su" to the new user first and then run the ssh-keygen command, that should create a key pair for the new user.

It was a while ago that I wrote this, I think I tried that approach first but then had an issue getting the key scp'd back to my laptop to give to the user. :)

@gitcoleman
Copy link

Got it, thanks!

@gitcoleman
Copy link

Hi Rob,

This is what I was talking about when I said it creates a key for the logged in user, not the new user.

image

I’ve underlined the part in red that I was concerned about.

image

Regards,
Wes

@robmsmt
Copy link
Author

robmsmt commented Oct 5, 2021

I think that part is just a comment: https://serverfault.com/a/743551/598820

@gitcoleman
Copy link

gitcoleman commented Oct 5, 2021 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment