Website log-in with Perl and Mechanize
Asked Answered
R

2

6

So this is driving me crazy. Basically, when I hard-code my user name and password, I can log-in no problem. But I want to prompt the user to enter the username and password, as I would like to share this program with others. (the program is supposed to log into our courses site and download all of our course work info - lectures, hw, etc)

This code works:

use WWW::Mechanize;
use LWP;

my $username = 'user'; 
my $password = 'pass';

my $mech = WWW::Mechanize->new();
$mech -> cookie_jar(HTTP::Cookies->new());
$mech -> get('log-in url');
$mech -> form_name('theform');
$mech -> field ('username' => $username);
$mech -> field ('password' => $password);
$mech -> click ('log in');
print $mech-> content();

however, when I try and prompt the user to enter log-in info, it does now work. printing content returns the html of the log-in page, not the following page (courses page for said user)

use LWP;
use WWW::Mechanize;

my $login_url = 'log-in url';
print "\nUser name: ";
my $username = <>;
print "Password: ";
my $password = <>;

my $mech = WWW::Mechanize->new();
$mech -> cookie_jar(HTTP::Cookies->new());
$mech -> get($login_url);
$mech -> form_name('theform');
$mech -> field ('username' => $username);
$mech -> field ('password' => $password);
$mech -> click ('log in');
print $mech-> content();

this really makes no sense since they are essentially the same thing. I even typed in the username/password in quotes in the prompt and still no avail..... (i realize also that it wont be very easy to check without a website and log-in info, sorry about that)

Rehearsal answered 20/5, 2011 at 18:15 Comment(1)
You don't need to use LWP and $mech -> cookie_jar(HTTP::Cookies->new()); in your code -- Mechanize will work with cookies automatically.Cardinalate
A
13

You need to run chomp() on the input from the user:

my $username = <>;
chomp($username);

The text supplied by the user has a carriage return at the end, which is screwing up your login.

Antidepressant answered 20/5, 2011 at 18:17 Comment(3)
thank you! i wish the begin-perl books would mention that (probably do somewhere though I bet)Rehearsal
@Rehearsal Chapter 1 of the Camel Book has a Filehandles section that has: "the line-reading operation does not automatically remove the newline from your input line (your input would be, for example, "9\n")."Antidepressant
use Data::Dumper and print Dump $some_variable very often is strongly helpful. It will show "enter key" pressed by user. conclusion, when some data is fetched from external source, it should be parsed for eliminate unneeded or sometimes toxic chars. It is reason why perl has built in taint mode.Capsaicin
D
2

Although CanSpice is correct, you may also want to look at Term::ReadPassword, it provides the prompt, it hides the input AND it takes care of the chomp for you!

Decasyllabic answered 21/5, 2011 at 3:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.