On 2/21/10 Sun Feb 21, 2010 7:13 AM, "akabou" <aka...@free.fr> scribbled:
> Hello, everybody > > I have a csv file with firstname, lastname, group Group name or group number? > > and need to create user and group if it doesn't exist. > > But the problem is that i must not use useradd ou groupadd. > > I must read user from csv, and then check if user exist, and if group > exist. > > i've started like this, but i don't know how to check if user exist, > and group exist. Use a hash indexed by user name for user data, and another hash indexed by group (name or number or both) for group data (probably just a dummy entry to indicate the group exists). > > Here is the starting of my code. You should have here: use strict; use warnings; > > $file = './liste_etudiants.csv'; ... which will force you to put my $file = ... here and below for better error checking. > open (FICH,$file) ||die ("Fichier innexistant"); > > > > while ($line = <FICH>) > { > #on splie chauqe ligne > ($field1,$field2,$field3) = split (',', $line); I would use better variable names: my( $firstname, $lastname, $group ) = split(/,/,$line); > #on enlève le charcatère " > ($field1) =~ s/"//g; > ($field1) = substr($field1, 0, 1); > ($field2) =~ s/"//g; > ($field3) =~ s/"//g; > ($login) = $field1 . $field2; The parentheses in the above lines are not needed and are confusing. > print "$field1 : $field2 : $field3 -- le login sera login$login sera > membre de $field3 \n"; > } > > #ecrire dans un fichier > #open(F_WRITE,">./touche.txt") || die "E/S : $!\n"; > #print $filed1; > > close(FICH); > > I wanted to test with tis kind of test > > open (FILE,"/etc/passwd"); > while () { > chomp; > /^([a-z][a-z0-9]*):x:([0-9]+):([0-9]+):/; > #si le user id=user id dans le fichier on incrémante de 1 le uid > if ($2 == $uid) { $uid++; } > } > > but don't know how. The /etc/passwd file has lines that are user records with fields separated by colons (':'). Use split to extract the fields (all untested): my @data = split(/:/); Save the data by user name: my( %users, %groups); ... $users{$data[0]} = \...@data; # or [...@data] to make a copy $groups{$data[3]} = 1; Do this before you read your CSV file. Then you can check if the user already exists with this: if( ! exists $users{$login} ) { # add user } or unless( exists $users{$login} ) { # add user } Note: some Unix systems have the file /etc/shadow that also must be modified to add a user. Read and save the contents of /etc/group similarly to see if the group exists. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/