Perl – Apache::Htpasswd

Imagine you set up dozens of virtual hosts and want each of them to have an individual default password for a protected area, i.e. a logfile directory being accessible via http://vhost/logs/. Putting .htaccess files into the target directories is step one and fairly simple. Whereas step two, adding the .htpasswd files, may end up unhandily, either juggling with cleartext and encrypted passwords or falling back on system() calls of htpasswd(2).

The example below shows how this can be handled with the modules Apache::Htpasswd and String::Random. Just provide a filename and a username, the subroutine will create the .htaccess file, add the user with a new random password and return the cleartext password to be handed out to your customer.

use String::Random;
use Apache::Htpasswd;

sub DefaultHtpasswd($$) {
  my($Filename,$Username) = @_;

  my $RandomString = new String::Random;
  my $PasswdString = $RandomString->randpattern('nnCcCnCc');

  my $Htpasswd = new Apache::Htpasswd($Filename);

  $Htpasswd->htpasswd($Username, $PasswdString, 1)
  or die($Htpasswd->error);


Comments are closed.