2

I need to generate a username and password pair in order to create user on a Unix system, preferably a pair that would be hard to guess (for security). Does anyone know any good way of doing this using Perl?

UPDATE

So I kind of combined some of the answers below and did some of my own stuff, and this it what I ended up getting. Now these generated usernames and passwords are kind of cryptic and not easy to remember, which is what I was looking for. However, if you're looking for more readable generation, you'll have to tweak it to your liking.

use String::Random qw(random_regex);
use Data::Random::WordList;
my $user = random_regex('\w{3,6}\d{3,6}\w{3,7}') . time . int(rand(1000)); 
my $wl = new Data::Random::WordList( wordlist => '/usr/share/dict/words' );
my @rand_words = $wl->get_words(int(rand(3)) + 3);
$wl->close();
my $pass = join " ", @rand_words;
$pass .= ' ' . int(rand(1000)) . time;
my $crypt_pass = crypt($pass,'salt');

system "useradd -p $crypt_pass $user";

#you can now login with $user and $pass on your system
srchulo
  • 5,143
  • 4
  • 43
  • 72
  • 1
    Have a look at the answer for http://stackoverflow.com/questions/6949667/what-are-the-real-rules-for-linux-usernames-on-centos-6-and-rhel-6 to get an idea of the limitations, you should then be able to generate what you need with a random number generator. Sorry, my Perl is a bit rusty but I may try to create an example. – Intermernet May 22 '13 at 04:00
  • @Intermernet, thanks! That link is really useful. And luckily I'm on CentOS 6 :) – srchulo May 22 '13 at 04:03

3 Answers3

2

For generating password You can use:

$password = `date | md5sum | fold -w 10 | head -n 1`;
$password = crypt($password,'some_string');

It's actually more Bash than Perl but it does the job.

Grzegorz Piwowarek
  • 13,172
  • 8
  • 62
  • 93
  • but what salt should I use with the `crypt` function? Will any salt work for the `useradd` command? – srchulo May 22 '13 at 04:32
  • @srchulo Any password generated by `crypt` will work with the `useradd`. According to the documentation You should use string that matches: [a-zA-Z0-9./] for salt – Grzegorz Piwowarek May 22 '13 at 04:49
2

From http://sysadminsjourney.com/content/2009/09/16/random-password-generation-perl-one-liner/

perl -le 'print map { (a..z,A..Z,0..9)[rand 62] } 0..pop' 8

Will generate a random 8 character string from the characters a-z, A-Z and 0-9 .

You should be able to modify this to generate the username and password.

Username would be:

perl -le 'print map { ([a-z_][a-z0-9_][rand 62] } 0..pop' 30

The password would be similar, but you would need to use the passwd command to actually set it to the user. Not sure if Perl has an equivalent.

Intermernet
  • 18,604
  • 4
  • 49
  • 61
2

As mentioned by others , its more BASH than perl. Here is my way of generating the password:

passwd=`date +%s | sha256sum | base64 | head -1 | cut -c 1-8`
slayedbylucifer
  • 22,878
  • 16
  • 94
  • 123