Reputation: 366
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
Upvotes: 0
Views: 2080
Reputation: 366
After trying several times, i made little changes that seems to work now.
#!/bin/bash
for u in `more sshuser.txt`
do
echo $u
sudo su - "$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
Upvotes: 1
Reputation: 530970
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
Upvotes: 3