Skip to content

Instantly share code, notes, and snippets.

@samjaninf
Created September 16, 2016 16:11
Show Gist options
  • Save samjaninf/2e61eb52099efa042688782a0a1ee95c to your computer and use it in GitHub Desktop.
Save samjaninf/2e61eb52099efa042688782a0a1ee95c to your computer and use it in GitHub Desktop.
Adding a list of users to each server
The best tool for this job is newusers. You will need to create a text file containing the list of users and their details. If you want to add the same user to each server, this file will only need one line.
Create the user's list. The general format of the file is
username:passwd:UID:GID:full name,room number,work phone,home phone,other:directory:shell
So, in your case, you would need to use something like
tom:password1:::"Tom Hanks","101","123456","654321","Tall"::
danny:password2:::"Danny DeVito","102","222333","333222","Short"::
Note that I have left the UID, GUID, directory and shell options empty. This means that default values will be used.
Now that you have created the list, you will need to copy it to each remote machine and then add the new users. For this, you will still need a list of relevant hostnames or IPs, one per line, as in my previous suggestion. Once you have all this set up, save this little script as newusers.sh:
#!/bin/bash
while read ip; do
scp users.txt root@$ip:/home/root
ssh root@$ip newusers users.txt
done
Make the script executable (chmod a+x newusers.sh) and run it for each IP in your file:
newusers.sh < IPs.txt
This will all be much easier if you have password-less ssh set up. If you don't, run the following commands to use ssh keys allowing password-less access (you will still need a passphrase):
ssh-keygen -t rsa
while read ip; do ssh-copy-id -i ~/.ssh/id_rsa.pub root@$ip; done < IPs.txt
Adding a different user to each server
In this case, I would create a slightly different file. It should have an IP or hostname, its corresponding user and the details needed to create her on each line. Assuming you want to set up passwords, you can have the plain text (obviously some security concerns here, don't know if they are relevant in your case) password as the fourth field. Also, in order to correctly parse names with spaces, make sure you use a non-space charcater as field separator. In the example below, I am using - :
192.168.1.10-tom-"Tom Hanks","101","123456","654321","Tall"-pass1
192.168.1.10-danny-"Danny DeVito","102","222333","333222","Short"-pass2
Now loop through the file and create each user on the corresponding machine. Make sure to set the IFS variabe to your field separator in order to parse spaces correctly:
while IFS='-' read ip name opts pass; do \
ssh root@$ip useradd $name -mc $opts -p `openssl passwd $pass` -s /bin/bash \
done < list.txt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment