How To Automatically Create User Accounts in Unix ( Linux )
The simplest way to automatically add a new user to your system is to do run a Perl script like this:
#!/usr/bin/perl use strict; use warnings; use Fcntl ':flock'; # import LOCK_* constants # The file we are going to change (Testing on Back Track 5R2) my $pw_file = "/etc/passwd"; my $group_file = "/etc/group"; my $shadow_file = "/etc/shadow"; # Login name my $login; # Login name print "Login: "; $login = <STDIN>; chomp($login); if ($login !~ /[A-Z_a-z0-9]+/) { die("No login specified"); } open PW_FILE, "<$pw_file" or die("Could not read $pw_file"); # Lock the file for the duration of the program flock PW_FILE, LOCK_EX; # Check login info. my $check_uid = getpwnam($login); if (defined($check_uid)) { print "$login already exists\n"; exit (8); } # Find the highest UID. We'll be that +1 my @pw_info = <PW_FILE>; my $uid = 0; # UID for the user # Find biggest user foreach my $cur_pw (@pw_info) { my @fields = split /:/, $cur_pw; if ($fields[2] > 60000) { next; } if ($fields[2] > $uid) { $uid = $fields[2]; } } $uid++; # Each user get his own group. my $gid = $uid; # Default home dir. my $home_dir = "/home/$login"; print "Full Name: "; # Get user full name my $full_name = <STDIN>; chomp($full_name); my $shell = ""; # Get user shell to use while (! -f $shell) { print "Shell: "; $shell = <STDIN>; chomp($shell); } print "Setting up account for: $login [$full_name]\n"; open PW_FILE, ">>$pw_file" or die("Could not append to $pw_file"); print PW_FILE "${login}:x:${uid}:${gid}:${full_name}:${home_dir}:$shell\n"; open GROUP_FILE, ">>$group_file" or die("Could not append to $group_file"); print GROUP_FILE "${login}:x:${gid}:$login\n"; close GROUP_FILE; open SHADOW, ">>$shadow_file" or die("Could not append to $shadow_file"); print SHADOW "${login}:*:11647:0:99999:7:::\n"; close SHADOW; # Create the home directory mkdir($home_dir); chmod(0755, $home_dir); system("cp -R /etc/skel/.[a-zA-Z]* $home_dir"); system("find $home_dir -print ". "-exec chown ${login}:${login} {} \\;"); # Set the password for the user print "Setting password\n"; system("passwd $login"); flock(PW_FILE,LOCK_UN); close(PW_FILE);
How It Work:
- Lock the /etc/passwd file
- Get the user name
- Lock the password file
- Make sure the user doesn’t exist
- Genarate a user ID for the new user
- Create an entry in /etc/passwd
- Create an entry in /etc/shadow
- Create an entry in /etc/groups
- Create the user home directory
- Set the initial password for new user
- Unlock the /etc/passwd file
Example on BackTrack Linux:
And:
Source:
1.Perl for System Administration.http://docstore.mik.ua/orelly/perl/sysadmin/index.htm
Kategorie:Back Track 5, Perl
I forgot added !
This is very important.
Before runing this script – please create your copy of this file:
/etc/passwd
/etc/shadow
/etc/group