Wednesday, December 21, 2011

Perl scripts to notify for your train reservation status


Two perl scripts to notify you when your train reservation status changes

To try out these scripts yourself, you will have to install the perl modules XML::XPathEngine,HTML::TreeBuilder and HTML::TreeBuilder::XPath.

pnrenq.pl

#!/usr/bin/perl

use strict;
use warnings 'all';

use HTTP::Request::Common;
use HTML::TreeBuilder::XPath;
use LWP::UserAgent;
$\ = "\n";
foreach my $pnr (@ARGV) {
    my $length = length ($pnr);
    my $lccp_pnrno1= substr ($pnr, 0, 3) ;    my $lccp_pnrno2= substr ($pnr, 3, 7) ;    if ( $length eq 10 ){
    
    my $ua = LWP::UserAgent->new;
    
    $ua->default_header('Accept'=>'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8');
    
    $ua->default_header('Accept-Charset'=>'ISO-8859-1,utf-8;q=0.7,*;q=0.3');
    
    $ua->default_header('Accept-Language'=>'en-GB,en-US;q=0.8,en;q=0.6');
    
    $ua->default_header('Cache-Control'=>'max-age=0');        $ua->default_header('Content-Type'=>'application/x-www-form-urlencoded');
    
    $ua->default_header('Host'=>'www.indianrail.gov.in');        
$ua->default_header('Origin'=>'http://www.indianrail.gov.in');
        $ua->default_header('Referer'=>'http://www.indianrail.gov.in/pnr_Enq.html');
        $ua->default_header('User-Agent'=>'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.63
Safari/535.7');
    
    my $response = $ua->request(POST 'http://www.indianrail.gov.in/cgi_bin/inet_pnrstat_cgi.cgi',
    
    [lccp_pnrno1 => $lccp_pnrno1,         lccp_pnrno2 => $lccp_pnrno2,         submitpnr => "Get+status"
   
     ]);
    
    if ($response->is_success) {
        
    my $tree= HTML::TreeBuilder::XPath->new;            
            $tree->parse_content($response->content);
            print $tree->findvalue('/html/body//table[@id="center_table"]//tr[count(td)=3]/td[3]');
        
    $tree->delete;
    
    }        else {
    
        die $response->status_line;
    
    }    }    else {
    
    print "\n InValid PNR\n\n";    }
}


op_change_mailer.pl

#!/usr/bin/perl

$cmd = $ARGV[0];
$op_file = $ARGV[1];
$prev_op = `cat $op_file`;
`$cmd > $op_file`;
$current_op = `cat $op_file`;

if ($prev_op ne $current_op) {
    system("cat $op_file | mail -s 'Status changed' [your mail id]");
    print "Sent mail\n";
}



Set up a cron with:
00 * * * 1-5 op_change_mailer.pl "pnrenq.pl [pnr numbers separated by spaces]" /var/tmp/pnr

No comments: