Randomuser1204281 Randomuser1204281 - 4 years ago 83
Bash Question

My script does not work properly

Problem:
I need to create a file where users and passwords are stored. But my script only saves the password of user1.

Example:
I explain myself better with an example. When the two users are created with random password, my script assigns the same password on both users.


user1:Eehei5oo8ohz:/home/user1:/bin/bash

user2:Eehei5oo8ohz:/home/user2:/bin/bash


When the result of my script should be something like this:


user1:Eehei5oo8ohz:/home/user1:/bin/bash

user2:Kln2149sdpja:/home/user2:/bin/bash


My script:
This is the script I have used:

#!/bin/bash
##Checking if you are root.##
if [ `id -u` -ne 0 ]
then
echo "you dont are a root user."
exit 1
fi

x=`pwgen 12 1`

for i in {1..2}
do
echo "user$i:@:/home/user$i:/bin/bash" >> users.txt
done

for j in $x
do
sed -i "s/@/$j/" users.txt
done


newusers users.txt

users=`cat users.txt`
login=`echo $i | cut -d: -f1` #username
pass=`cat pass.txt | tr " " _`
password1=`echo $i | cut -d: -f2` #password

for in $users
do
echo "$login:$password1" | chpasswd -m
done

rm users.txt
rm pass.txt


I hope I have explained correctly and appreciate all the help.

Answer Source

You can simplify this script by getting rid of sed editing, eg change:

for i in {1..2}
do
    echo "user$i:@:/home/user$i:/bin/bash" >> users.txt
done

for j in $x
do
    sed -i "s/@/$j/" users.txt
done

to

   pass=`cat pass.txt`
   i=1
   for pw in $pass
   do
          echo "user$i:$pw:/home/user$i:/bin/bash" >> users.txt
          ((i++))
   done

This way you can get user numbers and passwords in one go and you are guaranteed to get as many usernames as passwords.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download