0

I want to write a script in CentOs 7 that creates a new user for every CSV file row.

My csv file looks like this:

username;firstname;lastname;password
username2;firstname2;lastname2;
...
...

First column is the username, second is the first name, third is the last name and last column stands for password. If there isn't a password, it creates a user with some default value.

My code:

#!/bin/bash 

export IFS=";" 

cat users.csv | while read username name surname password; do 
    useradd "$username" -c "${name} ${surname}" -p "$password"
done

How do I create users from each column?

PesaThe
  • 7,259
  • 1
  • 19
  • 43
hrii00
  • 11
  • 2
  • Try something first, show some effort. For starters, read about `read` and `while` commands and how to read files with them. – PesaThe Jan 13 '18 at 17:28
  • I've already wrote this code – hrii00 Jan 13 '18 at 17:32
  • #!/bin/bash export IFS=";" cat users.csv | while read username name surname password; do useradd "$username" -c "${name} ${surname}" -p "$password" ; done – hrii00 Jan 13 '18 at 17:32
  • 1
    Don't post code in the comments, post it in the question. – PesaThe Jan 13 '18 at 17:32
  • it just creates users but I don't know how to set null columns into something else – hrii00 Jan 13 '18 at 17:33
  • yeah, sure. I've added my code to my answer – hrii00 Jan 13 '18 at 17:37
  • You need to adhere to the rules of creating unix usernames mentioned in this [\[ answer \]](https://stackoverflow.com/a/6949914/1620779). You should use the `crypt` method as mentioned in [\[ this \]](https://stackoverflow.com/a/1022024/1620779) answer when creating passwords. Also, it is better to sanitize the file before passing it to the `useradd` command. I would typically use `perl` or `awk` for that. I may write an answer for this at the earliest, but unfortunately not now. – sjsam Jan 13 '18 at 17:39
  • See https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html to expand empty strings to a default. This seems like the wrong solution, though; you probably ought to lock accounts that don't have a unique password. – Todd A. Jacobs Jan 13 '18 at 20:11
  • Tangentially, you want to avoid the [useless use of `cat`](https://stackoverflow.com/questions/11710552/useless-use-of-cat) – tripleee Jan 17 '18 at 06:40

1 Answers1

1

Try this:

$ su - newuser
No passwd entry for user 'newuser' 

$ IFS=";" && echo "newuser;New;User;testpass" | while read username name surname password; do sudo useradd "$username" -c "${name} ${surname}" -p `openssl passwd -1 $password` -m; done

$ su - newuser
Password: 
newuser@my-desktop:~$ logout

$ cat /etc/passwd | grep newuser
newuser:x:1002:1002:New User:/home/newuser:
Konstantin Vustin
  • 6,521
  • 2
  • 16
  • 32