0

I'm working a script that create user and add a key for that user so he can use that key with his username to SSH into my VM

Ex. user = john

useradd -m john &&
cd ~/.ssh/ && 
rm -rf tmp_rsa* &&
ssh-keygen -t rsa -b 4096 -C "john@email.com" -N '' -f john_rsa &&
echo "#tmp_rsa" >> authorized_keys &&
cat john_rsa.pub >> authorized_keys &&
cat authorized_keys &&
service ssh restart &&
echo ">>> Done"

Is the above script is correct to acheive what I want ?

I tried connect with UN : john, and the key generated john_rsa.

I got

enter image description here


Thanks to @marosg and @Takkat

Here is my updated script

adduser -m john &&
cd ~/.ssh/ && 
rm -rf tmp_rsa* &&
ssh-keygen -t rsa -b 4096 -C "john@email.com" -N '' -f john_rsa &&
echo "#tmp_rsa" >> ~john/.ssh/authorized_keys &&
cat john_rsa.pub >> ~john/.ssh/authorized_keys &&
cat authorized_keys &&
echo ">>> Done"
pa4080
  • 30,621
code-8
  • 205

2 Answers2

3

There are couple of things wrong here:

  • you create user john and then you do nothing with this user any more

  • You are adding keys to YOUR user

  • remote user who needs to login here needs the private key from ssh keypair on the machine from which he is connecting

  • there is no need to restart ssh service after adding keys

What you need on client side

  • user generates ssh keypair and provides you public key of this keypair (ssh-keygen ...; cat id_rsa.pub)

What you need on server side is

  • add user john

  • add the public key provided by user to ~john/.ssh/authorized_keys (echo id_rsa.pub_provided_by_remote_user >> ~john/.ssh/authorized_keys)

marosg
  • 1,323
1

Try this


set -euo pipefail

DEV_GROUP="somegroup" sudo groupadd --force "${DEV_GROUP}"

function adduser() { local var_user="$1" shift local var_ssh_pub_key="$*" id --user "${var_user}" &>/dev/null || sudo useradd --gid "${DEV_GROUP}" --groups wheel,docker "${var_user}" echo "${var_user} ALL=(ALL) NOPASSWD:ALL" | sudo tee "/etc/sudoers.d/${var_user}" sudo --user "${var_user}" mkdir -p "/home/${var_user}/.ssh" sudo --user "${var_user}" touch "/home/${var_user}/.ssh/authorized_keys" echo "${var_ssh_pub_key}" | sudo --user "${var_user}" tee "/home/${var_user}/.ssh/authorized_keys" }

adduser someuser ssh-rsa AAAAB3NzaC1.... user@host

slesh
  • 111