Random password generator
From dbawiki
#!/usr/bin/perl
# ==============================================================================
# Name : random_password.pl
# Description : Generates a random password according to specific rules
#
# Notes : none
#
# Modification History
# ====================
# When Who What
# ========= ================= ==================================================
# 16-APR-13 Stuart Barkley Created
# ==============================================================================
$DEBUG=0;
my $password='';
my $RULES_PASSED=0;
sub debug {
my $msg = $_[0];
$DEBUG && print $msg;
}
# -------------------
# Generate a password
# -------------------
sub generate_password {
my ($pwlen) = @_;
return `head /dev/urandom | uuencode -m - | sed -n 2p | cut -c1-\${pwlen:-12};`
}
while (! $RULES_PASSED) {
$password=generate_password;
chomp($password);
# --------------------
# Apply business rules
# --------------------
#1. Has to start and end with an alphabetic character
if ($password !~ m/^[A-z].*[A-z]$/) {
debug "$password failed rule 1\n";
next;
}
#2. Has to contain at least 2 upper case characters
if ($password !~ m/[A-Z].*[A-Z]/) {
debug "$password failed rule 2\n";
next;
}
#3. Has to contain at least 2 lower case characters
if ($password !~ m/[a-z].*[a-z]/) {
debug "$password failed rule 3\n";
next;
}
#4. Has to contain at least 2 digits
if ($password !~ m/\d.*\d/) {
debug "$password failed rule 4\n";
next;
}
#5. Has to contain between 10 and 12 characters
if ($password !~ m/.{10,12}/) {
debug "$password failed rule 5\n";
next;
}
# -----------------
# Apply other rules
# -----------------
#6. Has to contain only printable characters
if ($password !~ m/[ -~]/) {
debug "$password failed rule 6\n";
next;
}
#7. Cannot contain certain special characters
if ($password =~ m|[\/\&\*\$]|) {
debug "$password failed rule 7\n";
next;
}
$RULES_PASSED=1;
}
print $password;