Generate an ssh-key file for multiple users on each server

advertisements

I have to create 60 ssh users on one of the servers. I created users using small user creation script which loops though each users from the user list. I'm trying to run the similar script which will generate sshkeys for each user.

#!/bin/sh
for u in `cat sshusers.txt
do
echo $u
sudo su - $u
mkdir .ssh; chmod 700 .ssh; cd .ssh; ssh-keygen -f id_rsa -t rsa -N '';
chmod 600 /home/$u/.ssh/*;
cp id_rsa.pub authorized_keys
done

when i run this script, it basically logs into all 60 users account but does not create. ssh dir or generate passwordless ssh.key. Any idea to resolve this would be greatly appreciated! Thanks


sudo su - $u starts a new shell; the commands that follow aren't run until that shell exits. Instead, you need to run the commands with a single shell started by sudo.

while IFS= read -r u; do
    sudo -u "$u" sh -c "
      mkdir .ssh
      chmod 700 .ssh
      cd .ssh
      ssh-keygen -f id_rsa -t rsa -N ''
      chmod 600 '/home/$u/.ssh/'*
      cp id_rsa.pub authorized_keys
      "
done < sshusers.txt