Randomuser1204281
Randomuser1204281

Reputation: 15

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.

Upvotes: 0

Views: 68

Answers (2)

Bogdan Stoica
Bogdan Stoica

Reputation: 4539

You could simplify your script and adapt it as follows (I'm referring to the first part only):

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

  for i in {1..2}
  do
      x=`pwgen 12 1`
      echo "user$i:$x:/home/user$i:/bin/bash" >> users.txt
  done

This will create a file users.txt like the one bellow:

user1:ohng3uxohYi9:/home/user1:/bin/bash
user2:Gah5kiehaemi:/home/user2:/bin/bash

I see no point in creating a file with users and then replacing the @ sign with a generated password since you can do that from the start!

Upvotes: 1

TheMP
TheMP

Reputation: 8427

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.

Upvotes: 0

Related Questions