Perl – Shell commands with pseudo-interaction

There are plenty of problems I have to solve by myself as they are connected with very specific needs. Today I had to create 20+ ftp (pureftp) accounts with “random” passwords and a quota. All happened on Ubuntu server so I decided to write a script to make my life easier.

What I decided to do is to write a perl script that will get one argument on the command line (username) and make an ftp account “username” with chrooted home directory “/some/path/to/ftp/username”. Not-fully random (based on md5 algorithm) password and username should be appended to a text files, containing all the passwords.

Here’s the Perl script:

#!/usr/bin/perl
use Digest::MD5 qw(md5_hex);

if(@ARGV!=1){
        usage();
        exit();
}

$user = $ARGV[0];
print "Adding user ${user} to FTP db.\n";
$pass = substr(md5_hex($user),0,5);
$string = "pure-pw useradd ${user} -u 33 -g 33"
 ." -d /some/path/${user} -N 100"
 ." <<EOP\n${pass}\n${pass}\nEOP";
$out = `$string`;

open(DAT,">>passwords.txt");
print DAT "User: ${user}|Pass: ${pass}\n";
close(DAT);

sub usage{
        print "Usage: adduser.pl username\n";
}

Here are some explanations. First of all, we will need md5_hex function to generate a password for our user:

use Digest::MD5 qw(md5_hex);

If the user will run our script with more or less than one parameter (which should be the username) we should tell him how to use our script and exit.

if(@ARGV!=1){
        usage();
        exit();
}

#...

sub usage{
        print "Usage: adduser.pl username\n";
}

We get the username from the command line and save it as $user variable.

$user = $ARGV[0];
print "Adding user ${user} to FTP db.\n";

Next, we generate a password based on the md5 sum of the username. You can use salt or some randomness for increased security:

$pass = substr(md5_hex($user),0,5);
# for increased security you might want to put some salt to this:
#$pass = substr(md5_hex($user."salt"),1,5);

Now… the not-so-obvious part. We create a command for the command line. It gets interesting when the <<EOP begins. If you run pure-pw command it will prompt you for password and then retyping it. The part after “magic” <<EOP tells the script to get more input until it will find EOP line. This is how we force our script to get password from us.

$string = "pure-pw useradd ${user} -u 33 -g 33"
 ." -d /some/path/${user} -N 100"
 ." <<EOP\n${pass}\n${pass}\nEOP";
$out = `$string`;

-u and -g are here for system user and group connected with this ftp account. In my case it was www-data user and group. The last part is to append user’s username and password as a new line in a file:

open(DAT,">>passwords.txt");
print DAT "User: ${user}|Pass: ${pass}\n";
close(DAT);

This one is pretty straight forward.

Leave a comment

Your email address will not be published. Required fields are marked *