LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Adding users from file using PERL? (https://www.linuxquestions.org/questions/programming-9/adding-users-from-file-using-perl-608479/)

happy13 12-21-2007 10:16 PM

Adding users from file using PERL?
 
I am trying to use perl to add user accounts to my new server. I have the file which holds the usernames and passwords in this format:

username: password (no space between the : and word password)
username2: password (did it here because a funny face showed up)

and so on. I am trying to create a perl script that will read from this file and create the user accounts but am having trouble reading them one after another from the file and I don't seem to get the split function to work correctly. Please Help. Thanks in advance.

happy13 12-21-2007 10:25 PM

This is what I have so far:

#!/usr/bin/perl
open(FILE,"users") || die "Can't open file:$!\n";
@raw_data=<FILE>;
close(FILE);
foreach $user(@raw_data)
{
chop ($user);
($username, $password) = split(":", $user);
crypt($password, xx);
system("useradd -m -p $password $username -g groupname");
}

I am receiving an error that no sub routine is defined for system.

ghostdog74 12-21-2007 11:55 PM

Code:

open(FILE,"file") || die "Can't open file:$!\n";
@raw_data=<FILE>;
close(FILE);
foreach $user(@raw_data)

    ($username, $password) = split(":", $user);
    chomp($username); chomp($password);
    my $p = crypt($password, xx); # check perldoc -f crypt on how to generate random salt
    my $cmd = qq(useradd -m -p $p $username -g groupname); #define your groupname variable
    print $cmd ."\n";
  # system($cmd); #uncomment when needed
}


chrism01 12-22-2007 07:26 PM

Do these changes:

after
@raw_data=<FILE>;
add
chomp(@raw_data);

also, split uses a regex style normally, so
($username, $password) = split(/:/, $user);

don't split the individual fields.

Note chomp(), not chop() .. 2 different operators and you want the first one here.
http://perldoc.perl.org/functions/chomp.html
http://perldoc.perl.org/functions/split.html
Also, due to precedence issues, when checking file open etc, use 'or' not '||' .


All times are GMT -5. The time now is 02:00 PM.