Thursday, October 30, 2014

Autoposting to twitter account using WWW::Mechanize module (No More Functional Just An Example For Working With WWW::Mechanize Module)

WWW::Mechanize module is used for automatic interaction with websites, this method is also termed as web scrapping, it helps a Perl program to interpret as an individual website visitor and perform many actions automatically on behalf of the individual user. 
In the following example we have used this module for automatic posting of twit/ message into a twitter account, scrapping twitter mobile website.

#!/usr/bin/perl

use WWW::Mechanize; # required module for webpage scrapping

my $twitter_username = 'provide here twitter account username'; # twitter account username
my $twitter_password = 'provide here twitter account password'; # twitter account password

my $message = 'Hello Folks!!!'; # twit to be posted in the twitter account

my $uaa = "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13 ( .NET CLR 3.5.30729; .NET4.0C)"; # specifying the browser agent

my $mech = WWW::Mechanize->new( agent => $uaa ); # creating an object of mechanize module 

$mech->get('https://mobile.twitter.com/session/new'); # calling the required url and fetching the webpage

$authenticihty_token = $mech->field('authenticity_token'); # fetching the authenticity token value from a hidden field named 'authenticity_token' in the fetched webpage, which is required for logging into this website

$mech->post( 'https://mobile.twitter.com/session', { authenticity_token => $authenticihty_token, username => $twitter_username, password => $twitter_password } ); # posting the required values to another url for further processing ( here it is logging into the mobile twitter website )

$mech->post( 'https://mobile.twitter.com/', { authenticity_token => $authenticihty_token, commit => 'Tweet', 'tweet[text]' => "$message" } ); # posting the twit/ message in the twitter account 

if ( $mech->success() ) # returns true if earlier mechanize posting was successful
{
 print qq{Twitter posting successful\n};
}
else
{
 print qq{Twitter posting unsuccessful\n};
}


Output:
-------
On running the Perl script from command line, it will post the specified message into the twitter account mentioned in the script.

Saturday, October 25, 2014

Retrieving source of web pages and doing a bit more using LWP::UserAgent

The following program shows how to do something more along with retrieval of any web page source, like handling of cookies stored by the web page, specifying a desired browser agent for calling the web page and posting values to a web page.
#!/usr/bin/perl

use LWP::UserAgent; # required module to retrieve the source of any web page

use HTTP::Cookies; # required module for handling cookies

my $ua = new LWP::UserAgent; # create an object of LWP::UserAgent module to access it's methods

$ua->agent('Mozilla/8.0'); # specifying a browser agent, if required

# storing cookies in the file mentioned
$ua->cookie_jar(
 HTTP::Cookies->new(
  file => 'mycookies.txt',
  autosave => 1
 )
);

# posting values to a web page and retrieving it's source
my $response = $ua->post("http://www.hisdates.com/index.html",{name => "James Dcosta",age => "36"});

# on successful retrieval of the web page source, display the same on the screen else display the error message 
if ($response->is_success) {
 print $response->content;
}
else
{
 print $response->status_line;
}


Output:
-------
On running the Perl script from command line, the html source for the webpage "http://www.hisdates.com/index.html" will be displayed on the screen. 

Retrieving source of web pages using LWP::Simple

A simple example to show how to fetch a web page source and display on the screen.
#!/usr/bin/perl

use LWP::Simple; # required module to retrieve the source of any web page

my $content = get("http://www.hisdates.com/index.html"); # retrieving the source of web page and storing in a variable

print $content; # display the web page source on the screen


Output:
-------
On running the Perl script from command line, the html source for the webpage "http://www.hisdates.com/index.html" will be displayed on the screen. 

Friday, October 24, 2014

Copying files to and from a remote server using FTP in Perl

Following is a simple script to copy files to and from a remote server in the network using FTP.

#!/usr/bin/perl

use Net::FTP; # required module for FTP

my $ftp = Net::FTP->new('remoteserver ipaddress') or die "Cannot connect : $@"; # Connect to remote server for FTP

$ftp->login('username','password') or die "Cannot login :", $ftp->message; # Login to remote server using FTP username and password

$ftp->cwd("/var/www/test") or die "Cannot change directory :", $ftp->message; # Change working directory in the remote server for file transfer

$ftp->get("data.csv") or die "Cannot get file :", $ftp->message; # Fetching a file from the working directory (mentioned in the previous line using cwd) of remote server, to the working directory of the script in the running server

$ftp->put("/var/www/html/test.html") or die "Cannot put file :", $ftp->message; # Copying a file from the specified path of the script in the running server, to the working directory (mentioned in the previous line using cwd) of remote server

$ftp->quit(); # Closing the ftp connection



Output:
-------
On execution of the script, a FTP connection to the remote server will be opened and 'data.csv' file from '/var/www/test' location of the remote server will be copied to the working directory of the script running server and then '/var/www/html/test.html' from the specified location of the script running server will be copied to the '/var/www/test' location of the remote server.

A simple Perl script to send an email with attachment

Following is a simple email sending script in Perl, it also shows how to send an attachment file along with the email.

#!/usr/bin/perl

use MIME::Lite; # required module for formatting and sending the email using sendmail  

my $msg = MIME::Lite->new(
 From    => 'youraddress@youraddress.com', # sender email address
 To      => 'toaddress@toaddress.com',  # recipient email address 
 Cc      => 'ccaddress@ccaddress.com',  # optional, mention Cc recipient email address if required
 Type    => 'text/plain',   # main body type of the email, here it is text
 Subject => 'Email sending script exapmple', # mail subject line
 Data    => 'My first email sending perl script with an image file attachment', # main email body text
);

# the following portion is optional, required only in case of sending file attachments with the email 
$msg->attach(
 Type     =>'image/gif',   # attachment file type, here it is an image file
 Path     =>'/var/www/html/test.jpg', # location of the file in the server i.e to be attached with the email
 Filename =>'my_attachment.jpg'  # optional, only required for renaming the file attached in the email 
);

if ($msg->send()) # email sent and the returned status checked
{
 print "Mail sent successfully";
}
else
{
 print "Unable to send mail";
}


Output:
-------
It will send an email along with the attachment to the mentioned recipients on execution of the script.

Wednesday, October 22, 2014

File uploading script using CGI in Perl

Following is a simple example of uploading a file in the web server using Perl.

#!/usr/bin/perl

use CGI; # required module for CGI scripting

print "content-type: text/html \n\n";

my $q = new CGI; # create a CGI object

my $upload = $q->param("upload"); # using CGI param method to accept value passed to the program as a parameter

if ($upload) {
 &upload_file();
}
else
{
 &form();
}

sub form 
{
 print qq{
  
Upload Photo:
}; } sub upload_file { my $upload_dir = "/var/www/html/test"; my $filename = $q->param("photo"); # fetching the uploaded file name passed as posted parameter $filename =~ s/.*[\/\\](.*)/$1/; my $upload_filehandle = $q->upload("photo"); # fetching the content of the uploaded file open FL, ">$upload_dir/$filename"; while ( <$upload_filehandle> ) { print FL; } close FL; print qq{ Thankyou for uploading your photo!!!
}; }

Output:
-------
Considering the above script filename to be 'file_upload.pl' present inside the location '/var/www/cgi-bin/test/' of the web server, to checkout the file uploading functionality, please call the above script in the following format from a web browser:

http://server_address/cgi-bin/test/file_upload.pl

Tuesday, October 21, 2014

CGI scripting in Perl

In simple term CGI scripting in Perl denotes posting/ passing of values via get/ post method ( e.g: from a html form ) to a server side Perl script, which in turn accepts those values for further processing.

#!/usr/bin/perl

use CGI; # required for CGI programming

print "content-type:text/html\n\n"; # defining output type header

my $q = new CGI; # creating a CGI object, required here for accepting the values passed to the script

my $submit_value = $q->param('submit'); # accepting value of the submit button passed to the script on form submission

if ($submit_value eq '') {
 &form(); # if submit button is not clicked, a call is made to this subroutine to display the html form 
}
else
{
 &show(); # if submit button is clicked, a call is made to this subroutine to process the values passed from the html form 
}

sub form 
{
 # following displays the html form in the web browser
 print qq{
  
   
    My First CGI Script
   
   
    
Enter Your Name :

Enter Your Age :

Enter Your Address :

}; } sub show { # following accepts values of the text boxes present in the html form and passed to the script on form submission my $my_name_value = $q->param('my_name'); my $my_age_value = $q->param('my_age'); my $my_addr_value = $q->param('my_addr'); # following displays a html output, using the values passed to the script on form submission print qq{ Hello!!! My name is $my_name_value

I am $my_age_value years old

I live in $my_addr_value

Back }; }

Output:
-------
Considering the above script filename to be 'test_cgi.pl' present inside the location '/var/www/cgi-bin/test/' of the web server, to checkout the file uploading functionality, please call the above script in the following format from a web browser:

http://server_address/cgi-bin/test/test_cgi.pl

Now input your name, age, address in the text boxes provided, then click on submit and see the magic!!!