使用Perl生成随机密码
可以通过参数控制生成密码中包括的字符种类
#!/usr/bin/perl
usestrict;
usewarnings;
useGetopt::Std;
subshow_help{
print"Useage:\n";
print"newp-aAnsl\n";
print"-a\t\tthepasswordcontainslowercaseletters(a-z)\n";
print"-A\t\tthepasswordcontainsuppercaseletters(A-Z)\n";
print"-n\t\tthepasswordcontainsnumericalcharacter(0-9)\n";
print"-s\t\tthepasswordcontainsspecialsymbols\n";
print"-u\t\tthepasswordcontainsonlyuniquecharacters\n";
print"-llength\tsetthepasswordlength(default:6)\n";
exit0;
}
subshow_version{
print"Version:0.2.1Changedthedefaultoption:-l9-Ana.2016-4-15\n";
exit0;
}
###mainprogram
usevarsqw($opt_a$opt_A$opt_h$opt_l$opt_n$opt_s$opt_u$opt_v);
getopts('aAhl:nsuv');
&show_versionif$opt_v;
&show_helpif$opt_h;
my$len=$opt_l||9;#defaultlength9
my$opt_cnt=0;
my@rand_str=();
#storeallthecharacters
my@num=qw(0123456789);
my@ABC=qw(ABCDEFGHIJKLMNOPQRSTUVWXYZ);
my@abc=qw(abcdefghijklmnopqrstuvwxyz);
#my@sym=qw(!"$%&'*+-./:;<=>?@[\]^_`{|}~);
my@sym=qw(!$%&*+-./:;<=>?@[]^_`{|}~);#no"'\
unshift(@sym,'(',')','#',',');#topreventperl'scomplainsorwarnings.
my@all_sym=(@num,@ABC,@abc,@sym);
my@ch_src=();
if((!$opt_a)&&(!$opt_A)&&(!$opt_n)&&(!$opt_s)){
$opt_a++;
$opt_A++;
$opt_n++;
}
if($opt_a){
$opt_cnt++;
my$i=rand@abc;
unshift@rand_str,$abc[$i];
if($opt_u){
if($i>=1){
$abc[$i-1]=shift@abc;
}else{
shift@abc;
}
}
unshift(@ch_src,@abc);
}
if($opt_A){
$opt_cnt++;
my$i=rand@ABC;
unshift@rand_str,$ABC[$i];
if($opt_u){
if($i>=1){
$ABC[$i-1]=shift@ABC;
}else{
shift@ABC;
}
}
unshift(@ch_src,@ABC);
}
if($opt_n){
$opt_cnt++;
my$i=rand@num;
unshift@rand_str,$num[$i];
if($opt_u){
if($i>=1){
$num[$i-1]=shift@num;
}else{
shift@num;
}
}
unshift(@ch_src,@num);
}
if($opt_s){
$opt_cnt++;
my$i=rand@sym;
unshift@rand_str,$sym[$i];
if($opt_u){
if($i>=1){
$sym[$i-1]=shift@sym;
}else{
shift@sym;
}
}
unshift(@ch_src,@sym);
}
if($len<$opt_cnt){
print"Thecountofcharacters[$len]shouldnotbesmaller".
"thancountofcharactertypes[$opt_cnt].\n";
exit-1;
}
if($opt_u&&$len>(@ch_src+@rand_str)){
print"Thetotalnumberofcharacters[".(@ch_src+@rand_str).
"]whichcouldbecontained".
"inpasswordissmallerthanthelength[$len]ofit.\n";
exit-1;
}
foreach(1..$len-$opt_cnt){
my$i=rand@ch_src;
unshift@rand_str,$ch_src[$i];
if($opt_u){
if($i>=1){
$ch_src[$i-1]=shift@ch_src;
}else{
shift@ch_src;
}
}
}
foreach(1..$len){
my$i=rand@rand_str;
print$rand_str[$i];
if($i>=1){
$rand_str[$i-1]=shift@rand_str;
}else{
shift@rand_str;
}
}
print"\n";
exit0;
以上就是本文给大家分享的全部代码了,希望对大家学习Perl能够有所帮助