Wednesday 14 June 2017

Add users via receipt of user and password inputs from different files

I recently came across a question where in an admin wanted to create multiple users on Linux servers and had the password and user information contained in different files. If it were the same password for all users then that would've been easy to loop over but this was different because the user name and passwords were both unique.

So, here are sample files for lists of user names and password.

[root@pbox ~]# cat users
james
john
[root@pbox ~]# cat passwords
james123
john123

Now instead of coming up with a logic to run a loop with two variables I decided it would be easier to just combine the two files via paste command.

[root@pbox ~]# paste -d ' ' users passwords > creds
[root@pbox ~]#

So now the creds file looks like this:

[root@pbox ~]# cat creds
james james123
john john123


With the two file problem sorted the user creation process was a one line while loop away.

[root@pbox ~]# cat creds | while read user pass; do useradd $user ; echo $pass | passwd --stdin $user;done
Changing password for user james.
passwd: all authentication tokens updated successfully.
Changing password for user john.
passwd: all authentication tokens updated successfully.
[root@pbox ~]#

I hope this article was helpful to you and gives some interesting scripting ideas!
Thank you for reading.

No comments:

Post a Comment

Using capture groups in grep in Linux

Introduction Let me start by saying that this article isn't about capture groups in grep per se. What we are going to do here with gr...