Wednesday, November 16, 2011

How to have password prompts in perl script

The below code will help your scripts to have password prompts without echoing it to console. This will help you in hiding the password while running the scripts.



Subroutine

sub getadmininfo() {
        print "Enter username: ";
        chomp (my $adminusername = <STDIN>);
        print "Enter password: ";
        system('stty','-echo'); #Hide console input for what we type
        chomp(my $adminpassword=<STDIN>);
        system('stty','echo'); #Unhide console input for what we type
        print "\n";
        return (\$adminusername,\$adminpassword);
}



Call subroutine using

 my ($adminusername,$adminpassword)= &getadmininfo();


1 comment:

  1. If you download Term::ReadKey you can do something like the following:

    use Term::ReadKey;

    sub get_password {
    my $password;
    print "Enter password: ";
    ReadMode 'noecho';
    $password = ReadLine 0;
    chomp $password;
    ReadMode 'normal';
    print "\n\n";
    return $password;
    }

    ReplyDelete