Adhz
Adhz

Reputation: 55

Shell script to create linux users where username and password are read from a config file

I am trying to develop a shell script which creates new users in linux machine. Where username and password are fetched from a config file. Can somebody help me to create a script which creates users with all the usernames in the config file.

My config file contains (myconf.cfg)

username="tempuser"
password="passXXX"

username="newuser"
password="ppwdXXX"
.....
.....

username="lastuser"
password="pass..."

Using a script I am trying to create users with above listed username and password. The script is:

#!/bin/sh 

echo "Reading config...." >&2
. /root/Downloads/guest.cfg

pass=$(perl -e 'print crypt($ARGV[0], "password")' $password)

sudo useradd -m -p $pass $username -s /bin/bash

I am able to create only 1 user with this script (ie lastuser). Can somebody help me to modify the script and config file so that it will create all the users mentioned in the config file. My aim is to keep the script intact and make changes to the config file only. The script should be able to create 'N' number of users listed in the config file.

Thanks in advance.

Upvotes: 1

Views: 1362

Answers (1)

Andreas Louv
Andreas Louv

Reputation: 47099

The problem is that you source guest.cfg which will set the variable username and password multiply times, each time overriding the previous set. You need to parse the config file.

One way - assuming there is no newline in the usernames/ passwords - is with sed:

sed -n -e 's/\(password\|username\)="\(.*\)"/\2/gp' guest.cfg

This will print lines that match the patterns: username="..." and password="..." so for instance with your example the output will be:

tempuser
passXXX
newuser
ppwdXXX
lastuser
pass...

As you can see you now got this pattern:

username
password
username
password
...

This can be utilized in a while loop:

sed -n -e 's/\(password\|username\)="\(.*\)"/\2/gp' guest.cfg \
  | while IFS= read -r line; do
    if [ -n "$username" ]; then
      password="$line"
      # Do stuff with $username and $password
      # ...
      # At the end you need to unset the username and password:
      username=
      password=
    else
      username="$line"
    fi
  done

Upvotes: 1

Related Questions