Showing posts with label Perl. Show all posts
Showing posts with label Perl. Show all posts

Monday, July 27, 2009

Perl ImageMagick convert Images from one format to another

Introduction
A Picture speaks louder than a thousand words. Most of the programming problems I usually worked with and involved in where dealing with just TEXT. So now I wanted to programatically work with images. I needed to warp, rotate, scale, stretch, convert from jpeg to png, png to jpeg, jpeg to bmp, bmp to jpeg etc. So I decided to search on how to do such a thing easily. Well the first obvious answer is to do handle all these in C reading files uncompressing based on the extensions, compressing, write the encoders and do whole lot of "Reinventing the wheel" stuff. So I found this software called ImageMagick which already wrote the codes to do all these for you, and what more? It has a neat Perl API so that you can do the fun stuff that you do on perl on images. Now that's sweet.

Hello World
Now just check out this simple script to convert files from one format to another.


#!/usr/bin/perl
#
#usage: perl im.pl <Source File> <Destination File>
#

use strict;
use Image::Magick;

my $q = Image::Magick->new;

my $source = $ARGV[0];
my $dest = $ARGV[1];

$q->Read($source);
$q->Write(filename=>$dest);

exit;


That is all that is required to convert file from one format to another using ImageMagick and the Perl Image Magick API. For example
perl im.pl IMG_0021.JPG IMG_0021.BMP

would convert the JPG to BMP for you.

Wednesday, July 8, 2009

yum/apt-get update Breaks Perl CPAN

Doing an yum update or apt-get update and upgrading your system might break the PERL installation, the output I got while doing so: (after an update).


[root@desktop]# cpan

cpan shell -- CPAN exploration and modules installation (v1.7602)
ReadLine support enabled

cpan> install WWW::Mechanize
CPAN: Storable loaded ok
Going to read /root/.cpan/Metadata
Database was generated on Mon, 15 Jun 2009 02:27:28 GMT
Going to read /root/.cpan/sources/authors/01mailrc.txt.gz
CPAN: Compress::Zlib loaded ok
Going to read /root/.cpan/sources/modules/02packages.details.txt.gz
Database was generated on Wed, 08 Jul 2009 02:28:24 GMT
CPAN: HTTP::Date loaded ok

There's a new CPAN.pm version (v1.9402) available!
[Current version is v1.7602]
You might want to try
install Bundle::CPAN
reload cpan
without quitting the current session. It should be a seamless upgrade
while we are running...

CPAN: LWP::UserAgent loaded ok
Fetching with LWP:
ftp://ftp.jaist.ac.jp/pub/CPAN/modules/03modlist.data.gz
LWP failed with code[500] message[Errno architecture (i386-linux-thread-multi-2.6.18-53.1.14.el5pae) does not match executable architecture (i386-linux-thread-multi-2.6.18-53.el5) at /usr/lib/perl5/site_perl/5.8.8/Errno.pm line 11.
Compilation failed in require at /usr/lib/perl5/5.8.8/i386-linux-thread-multi/IO/Socket.pm line 17.
BEGIN failed--compilation aborted at /usr/lib/perl5/5.8.8/i386-linux-thread-multi/IO/Socket.pm line 17.
Compilation failed in require at /usr/lib/perl5/5.8.8/Net/FTP.pm line 18.
BEGIN failed--compilation aborted at /usr/lib/perl5/5.8.8/Net/FTP.pm line 18.
Compilation failed in require at /usr/lib/perl5/site_perl/5.8.8/LWP/Protocol/ftp.pm line 21.
]
Fetching with Net::FTP:
ftp://ftp.jaist.ac.jp/pub/CPAN/modules/03modlist.data.gz
Can't locate object method "new" via package "Net::FTP" at /usr/lib/perl5/5.8.8/CPAN.pm line 2250.


This is due to the architecture check and differences that PERL encounters on Errno.pm module.

Fix
This can be called a fix or rather a tweak by commenting out these lines (Add #'s to the beginning) on
/usr/lib/perl5/site_perl/5.8.8/Errno.pm


"$Config{'archname'}-$Config{'osvers'}" eq
"i386-linux-thread-multi-2.6.18-53.1.14.el5pae" or
die "Errno architecture (i386-linux-thread-multi-2.6.18-53.1.14.el5pae) does not match executable architecture ($Config{'archname'}-$Config{'osvers'})";

Change the lines to:

#"$Config{'archname'}-$Config{'osvers'}" eq
#"i386-linux-thread-multi-2.6.18-53.1.14.el5pae" or
# die "Errno architecture (i386-linux-thread-multi-2.6.18-53.1.14.el5pae) does not match executable architecture ($Config{'archname'}-$Config{'osvers'})";

Sunday, February 1, 2009

PERL Code to change Google talk status

Code : stat.pl
The following code changes the status of gmail/gtalk user status.
Requires NET::XMPP module, and with SSL modules installed.


#!/usr/bin/perl
#usage : perl stat.pl <status>
use strict;
use Net::XMPP;


## Pls fill in these here :)
my $username = "";
my $password = "";


my $hostname = 'talk.google.com';
my $port = 5222;
my $componentname = 'gmail.com';
my $connectiontype = 'tcpip';
my $tls = 1;

my $Con = new Net::XMPP::Client(debuglevel=>0);

my $status = $Con->Connect(
hostname => $hostname,
port => $port,
componentname => $componentname,
connectiontype => $connectiontype,
tls => $tls,
timeout => 10);

if (!(defined($status))) {
exit(0);
}

my $sid = $Con->{SESSION}->{id};
$Con->{STREAM}->{SIDS}->{$sid}->{hostname} = $componentname;

my @result = $Con->AuthSend(
username => $username,
password => $password,
resource => "neuron");

$Con->Send("<iq type='get' to='gmail.com'><query xmlns='http://jabber.org/protocol/disco#info'/></iq>");
$Con->Process();

my $iq = $Con->SendAndReceiveWithID("<iq type='get' to='$username\@gmail.com'><query xmlns='google:shared-status'/></iq>");

my ($status,$statuslist,$show) = ("","","");
$status = $1 if($iq->GetXML() =~ m/<status>(.*?)<\/status>/);
$statuslist = $1 if($iq->GetXML() =~ m/(<status-list(.*)<\/status-list>)/);
$show = $1 if($iq->GetXML() =~ m/<show>(.*?)<\/show>/);

my $status = $ARGV[0];

#Change status
$Con->Send("<iq type='set' to='$username\@gmail.com'><query xmlns='google:shared-status'>
<status>$status</status><show>$show</show>
$statuslist
</query></iq>");
$Con->Process();
$Con->PresenceSend(type=>'unavailable');
$Con->Process();
$Con->Disconnect();
$Con->Process();
exit;


Usage
perl stat.pl "my status"


Worked? or Crap?
Lemme know....
;)

Sunday, June 29, 2008

Dataone Account Usage Checker in PERL

The following Script in PERL is a Dataone account usage checker.


#!/usr/bin/perl
# http://digitalpbk.blogspot.com/2008/06/free-dataone-account-usage-checker-perl.html

use WWW::Mechanize;
use HTTP::Cookies;
use HTTP::Request::Common;

my $verbose = 0;
my $username;
my $password;
my $url="http://10.240.64.195/weblogin.jsp";

for(my $i=0;$i<=$#ARGV;$i++)
{
if($ARGV[$i] eq "-v" or $ARGV[$i] eq "--verbose"){ $verbose = 1; }
elsif($ARGV[$i] eq "-u" or $ARGV[$i] eq "--user"){ $username = $ARGV[++$i]; }
elsif($ARGV[$i] eq "-p" or $ARGV[$i] eq "--pass"){ $password = $ARGV[++$i]; }
elsif($ARGV[$i] eq "-i" or $ARGV[$i] eq "--url"){ $url = $ARGV[++$i]; }
}
unless($username)
{
print "Username : ";chomp($username = <STDIN>);
}
unless($password)
{
print "Password : ";
`stty -echo`;
chomp($password = <STDIN>);
`stty echo`;
print "\n";
}
$cj = HTTP::Cookies->new(file => "cookie.jar",autosave=>1);
$mech=WWW::Mechanize->new(cookie_jar=>$cj);

print "GET $url\n" if($verbose);
$mech->get($url);
exit unless($mech->success());

my $cnt = $mech->response->as_string;

$cnt =~ s[action="../(.*?)"][action="$1"]is;
$mech->update_html($cnt);

$mech->form_number(1);
$mech->field("username",$username);
$mech->field("password",$password);
print "LOGIN\n" if($verbose);
$mech->submit();

exit unless($mech->success());
$cnt = $mech->response->as_string;

$|=1;
my $uri;my $maxre=0;
while($cnt =~ m/location.replace\('(.*?)'\)/is)
{
print "FOLLOWING .. " if($verbose);

$uri = $1;
if($uri =~ m/loginerr/g)
{
print "\nLOGIN Failed !\n";
exit;
}

$mech->get($uri);
exit unless($mech->success());
print $uri,"\n" if($verbose);
$cnt = $mech->response->as_string;
last if($maxre++ > 4);
}

exit if($maxre > 4);
print "GET Service Records\n" if($verbose);
$mech->get("serviceRecords.jsp");
exit unless($mech->success());
$cnt = $mech->response->as_string;

$mech->form_number(1);
$mech->submit();
print "POST Form\n" if($verbose);

$cnt = $mech->response->content;
$cnt = $1 if($cnt =~ m:<body[^>]*>(.*?)</body>:sig);

$cnt =~ s/<[^>]+>//sig;
$cnt =~ s/&nbsp;/ /sig;
$cnt =~ s/([\n\r\t ]){2,}/;/sig;

$cnt = $1 if($cnt =~ m/(Total Send Volume([^;]+;){10})/);

@sl = split /;/,$cnt;

$sl[4] = "Excluding Night";
for($i=0;$i<=($#sl/2);$i++)
{
printf("%25s : %s\n",$sl[$i],$sl[$i+5]);
}

$mech->get("../logout.jsp");



Installation

On Linux
Copy paste to a new file data1.pl
Install WWW::Mechanize if not already installed.

chmod 755 data1.pl


On Windows
Copy paste to a new file data1.pl
Get Active Perl and install if PERL is not installed.
Install Module WWW::Mechanize.

Usage
Linux
./data1.pl Options


Windows, not TESTED
perl data1.pl Options

PS : Comment `stty` lines when using on windows or ignore the errors
perl data1.pl -u username -p password


Options
No need any if your not good at the Command line.
-v to turn on Verbose, describe what is being done.
-u username to specify username
-p password to specify password

...
Any more doubts ?
Use the link that says comment
;)


100th

Post

Saturday, June 14, 2008

Perl Download Manager

Intro
This is my PERL downloader program, with resume.
Only works if SERVER has Parts enabled.
Well pretty much thats it



#!/usr/bin/perl

use strict;
use threads;
use threads::shared;
use HTTP::Request;
use HTTP::Response;
use Math::Round qw(nearest);
use LWP;



exit unless(defined $ARGV[0] && -e $ARGV[0]);

open HND,$ARGV[0];
NEXT:
while(my $url = <HND>)
{
my $file = substr($url,rindex($url,"/")+1);
$file =~ s/%20/_/g;

chomp $url;

exit if($url eq "" || $file eq "");

print "Downloading $url \n to $file \n";


our @stats:shared = (0,0,0,0,0,0,0,0,0,0,0,0,0,0);
our $exit:shared = 0;
our $tdl:shared = 0;
our $tgl:shared = 0;

our $lastime:shared = time();
our $lasdl:shared = 0;

my $folder = "/home/arun/download/";

select STDOUT; $| = 1;

sub catchintr()
{
my $who = shift;
print "\n$who is Bugging me\nDownload Paused\nExit message dispatched";
$exit = 1;
}

$SIG{INT} = \&catchintr;
$SIG{HUP} = \&catchintr;

sub dloader
{
select STDOUT; $| = 1;

my ($inx,$url,$localfile,$blockstart,$blockend) = @_;

my $length = $blockend - $blockstart + 1;

my $stbit = 0;
if(-f $localfile)
{
open HND, $localfile or die $!;
binmode HND;
seek HND,0,2;
$stbit = tell HND;
close HND;
$tdl += $stbit;
}
else
{
open HND,">$localfile" or die $!;
print HND "";
close HND;
}

my $ua = LWP::UserAgent->new;

my $pcksize = 1024*64;

my $enbit = $stbit+$pcksize-1;
my $parts = int($length / $pcksize)+1;
$enbit = $length - 1 if($enbit > $length);
my $err =0;
my $i = int($stbit / $pcksize);

my $req = HTTP::Request->new('GET',$url);

if($stbit >= $length)
{
print "$localfile Part Complete! $length <=> $stbit\n";
$stats[$inx] = 1;
return;
}
while($stbit < ($length-1) && $err < 100)
{
my $stbit2 = $stbit + $blockstart;
my $enbit2 = $enbit + $blockstart;

my $range = "bytes=$stbit2-$enbit2";
$req->header('Range' => $range);

$i++;

print "\n $inx ... $i / $parts ";
my $res = $ua->request($req);

threads->yield();

if($res->code == 206)
{

open HND, ">>$localfile";
binmode HND;
print HND $res->content;
close HND;

$stbit = $stbit + $pcksize;
$enbit = $stbit + $pcksize - 1;
$enbit = $length - 1 if($enbit > $length);

$tdl += $pcksize;


if($tdl < 1024)
{
print "[$tdl] bytes";
}
elsif($tdl < 1024 * 1024)
{
print "[".nearest(0.01,$tdl/1024,)." KB]";
}
else
{
print "[".nearest(0.01,$tdl/1048576)." MB]";
}

if((time()-$lastime) > 0)
{
print " [ ".nearest(0.01,($tdl-$lasdl) / (1024 * (time() - $lastime) ) ). " kB/s ] ";
$lasdl = $tdl;
$lastime = time();
}

}
elsif($res->code == 416)
{
print "\n\nSeems complete";
exit;
}
else
{
print "\nGlitch $err : ";
print $res->code;
print "\nResuming...\n";
sleep 1;
$i--;
$err++;
}

if($exit)
{
print "\n$inx is exiting ";
$stats[$inx] = 1;
return 0;
}

}
if($err == 100)
{
print "\nToo many errors in $inx, killing everyone\n";
$exit = 1;
}

$stats[$inx] = 1;
return $err;
}
my $errls = 0;

REDO:
my $req = HTTP::Request->new('HEAD',$url);
print $req->as_string;
my $ua = LWP::UserAgent->new;

my $res = $ua->request($req);

print $res->as_string;
if($res->code != 200)
{
print "\n\n";
goto REDO if($errls++ < 10);
}


my $length = $res->header('Content-Length');
$tgl = $length;
my $req = HTTP::Request->new('HEAD',$url);
$req->header('Range' => 'bytes=0-99');
my $res = $ua->request($req);
print $res->as_string;
if($res->code != 206)
{
print "Parts cant be used!\n:(\n";
goto NEXT;
}

if(!defined $length)
{
$length=-1;
print "Missing Length
Any Idea? : ";
$length = <>;
print "\n";
}
my $blocks = 8;
my $blocksize = ($length + $blocks - $length % $blocks) / $blocks;
if($blocksize < 1024 * 512)
{
$blocks = 4;
$blocksize = ($length + $blocks - $length % $blocks) / $blocks;
}
#print $blocksize," ",$blocksize*$blocks," ",$length;

my $blockstart = 0;

my @thread = ();

print "\nthreading Gatherers ...\n";

my ($blockend);
for(my $i=1;$i<=$blocks;$i++)
{
$blockend = $blockstart + $blocksize;
$blockend = $length if($blockend > $length);
$thread[$i] = threads->new(sub{dloader($i,$url,$folder."$file.$i.part",$blockstart,$blockend)});
$blockstart = $blockend + 1;
}


my $flag = 0;

do
{
$flag = 0;
for(my $i=1;$i<=$blocks;$i++)
{
$flag = 1 if($stats[$i] == 0);
}
sleep 1;
}
while($flag);

if($exit)
{
open STAT,">>$folder"."$file.stat";
print STAT "".localtime;
print STAT " : Downloaded $tdl / $tgl bytes ".($tdl*100/$tgl)."%\n";
close STAT;
exit;
}

print "\n\ngathering Gatherers...\n";


print "\nMerging ... ";

open OUT,">$file";
binmode OUT;
for(my $i=1;$i<=$blocks;$i++)
{
print "\n+ ".$folder."$file.$i.part";
open IN, $folder."$file.$i.part";
binmode IN;
my $buffer;
print OUT $buffer while(read(IN,$buffer,65536));
close IN;

unlink $folder."$file.$i.part";
}
close OUT;
print "\nDone :)\n";
open STAT,">>$folder$file.stat";
print STAT "".localtime;
print STAT " : Finished Downloading $tdl / $tgl bytes \n";
close STAT;
}

close HND;

Monday, October 1, 2007

PERL Referencing and Dereferencing

Intro

PERL - Practical Extraction and Report Language.

Referencing a variable means creating a pointer to the variable.
Referencing in C is done by the & operator, but in PERL referencing is done by the \(backslash) operator.

Check out the following examples to understand better:

my $scalar = "http://digitalpbk.blogspot.com";
my $scalar_ptr = \$scalar; //Scalar reference

my $array= (1,2,4,3,5);
my $array_ptr = \@array; //Array reference
//or

my $array_ptr = [1,2,3,4,5];//Array reference
//Note the [Square brackets]


my %hash = ("one",1,"two",2);
my $hash_ptr = \%hash; //Hash reference
//or

my $hash_ptr = {"one" => 1,"two"=>2};//Hash reference
//Note the {Curly brackets}


my $sub_ref = \&a_subroutine;//Subroutine reference
//or

my $sub_ref = sub { print "somethings"; };//Sub reference




Dereferencing is the opposite of referencing i.e, to get the value pointed by the referencing/pointing variable. Dereferencing in C is done by the * operator, whereas in PERL it is done by prepending, adding an appropriate @,$ or % to the reference variable.



my $scalar_ptr = \$scalar; //Scalar reference
my $scalar = $$scalar_ptr; //Scalar Var

my $array_ptr = \@array; //Array reference
//or

my $array_ptr = [1,2,3,4,5];//Array reference
my $array = @$array; // Array Var


my $hash_ptr = \%hash; //Hash reference
my %hash = %$hash //Hash Var

my $sub_ref = \&a_subroutine;//Subroutine reference
my $sub_ref = sub { print "somethings"; };//Sub reference
&$sub_ref //Call Subroutine



Thats all about referencing and dereferencing...

Saturday, September 8, 2007

Perl - cPanel V3 and the @INC

Modifying @INC in a SCRIPT

use Module;

is executed during compile time so if you modify the @INC array at run time it will not be reflected back in the compile time. So if you have to include any more include locations in the @INC inside a script, give it inside the BEGIN { }block.


BEGIN
{
push @INC,"location";
}

The BEGIN blocks are executed during compile time. So @INC is updated at compile time and the use module are correctly searched for in the updated directories.

cPanel-v3 Script

my $homedir = (getpwuid($>))[7];
my $n_inc = scalar @INC;
for (my $i = 0; $i < $n_inc; $i++ ) {
if (-d $homedir . '/perl' . $INC[$i]) {
unshift(@INC,$homedir . '/perl' . $INC[$i]);
$n_inc++;
$i++;
}
}


This script dint work for me much, so I manually included the include locations into the BEGIN segment.


#! /usr/bin/perl -w
BEGIN {
unshift @INC,"/home/directory/perl/usr/lib/perl5/site_perl/5.8.7/";
}
.
.
.

Wednesday, July 4, 2007

cPanel Mail Forwarder

Forwarder

This handly little program forwardes all emails coming to a certain specified email address and forwards to a forwarding list.

Setting up the email capturing

e-Mail can be captured using a PERL script. The contents of the email must be pipped in. The capturing an passing of the email can be done through cPanel.


Click Mail

Click Forwarders

Add Forwarder


In the text box to the right side, you can provide an email address or a path to your PERL program that can process your email and extract relevant information.

In order to send the contents of the email to a PERL program we have to PIPE it to the program. PIPING is just redirection of standard output of the mail receiving program to your custom PERL script.
Eg:


"|perl /home/domain/scripts/process.pl"



#!/usr/bin/perl
use strict;


my $Email = join '',<STDIN>;

$Email // has your email contents

Sunday, June 17, 2007

Perl Script to HTML formatter

Intro
This script converts a Perl Script to HTML so that it looks good with colour code formatting for keywords and variables. This isn't yet completed and may contain bugs but I guess its worth posting. Anyone is free to modify and redistribute the code as long as the first line remains intact.

Usage


perl format.pl ScriptFile.pl

Output will be saved as ScriptFile.pl.html

Script

style="color:#0ff">$cnt =~ s/&/&amp;/g;

$cnt =~ s/</&lt;/g;

$cnt =~ s/>/&gt;/g;







#Keywords



$keywords =~ s/ /)|(?:/g;



#Comments

$cnt =~ s/$singlecomment(.*)\n/<span style="color:#080">$singlecomment$1<\/span>\n/g;



$cnt =~ s/(?:<.*?>)*([\s)\[{;])((?:$keywords))([\s\[{(;])(?:<\/.*?>)*/$1<span style="color:#008;font-weight:bold;">$2<\/span>$3/g;

$cnt =~ s/([^\\])([\@\$].*?)([^a-zA-Z0-9_])/$1<span style="color:#0ff">$2<\/span>$3/g;



print $ARGV[0].".html";

open FILE,">".$ARGV[0].".html";

print FILE "<pre>$cnt</pre>";

close FILE;




Found a bug? (Plenty I know)
Post a comment with Line Number , Code , Correction.

Orkut Perl Script - Login, Scrapper and more

Intro
This is a PERL script that logs you into Orkut and allows you to scrap yiur friends. Following is the program and beneath it lies the manual to use the program. I assume that you already have PERL installed on your system with the required modules:

  • LWP
  • WWW::Mechanize


Program
#! /usr/bin/perl -w

use WWW::Mechanize;
use HTTP::Cookies;
use HTTP::Request::Common;

use subs qw(print_c login logout home grab proces scrap);


#autoflush STDOUT 1;

printf ("%45s","Command Line Orkut\n");
printf ("%50s","By http://digitalpbk.blogspot.com\n");

#inits
$cj=HTTP::Cookies->new(file => "cookie.jar",autosave=>1,ignore_discard=>1);
$mech = WWW::Mechanize->new(cookie_jar => $cj);

@prc = ("\n","[FAILED]","[ OK ]\n");
#main loop
print_c;
while(<STDIN>)
{
chomp;
@args = split(/ /);

if(@args)
{
exit 0 if($args[0] eq "exit" || $args[0] eq "q");

if($args[0] eq "login") {login(@args);}
elsif($args[0] eq "home") {home(@args);}
elsif($args[0] eq "logout") {logout(@args);}
elsif($args[0] eq "grab") {grab(@args);}
elsif($args[0] eq "process") {proces(@args);}
elsif($args[0] eq "scrap") {scrap(@args);}
elsif($args[0] eq "populate") {populate(@args);}
elsif($args[0] eq "captchaget") {captchaget(@args);}
elsif($args[0] eq "clear") {system("clear");}
print "\n";
}
print_c;
}

exit 0;


sub print_c
{
print "";
print "> ";
print "";
}

sub login
{


print "\nGmail iD : ";
$email = <STDIN>;
print "Password : ";
$pass = <STDIN>;
print $prc[0];

chomp $email;chomp $pass;

RELOGIN:
for($i=3; $i>=0;$i--)
{
printf("%-60s","GET /Home.aspx");
$mech->get("http://www.orkut.com/Home.aspx");
last if($mech->success());

printf("%10s",$prc[1]);
print " Retry (",$i,")".$prc[0] if($i);
}

return if($i<=0);
print $prc[2];


$cnt = $mech->response->as_string;
$cnt =~ s/\n|\s+/ /g;

if($mech->title =~ m/orkut.*home/i)
{
print "\nAlready Logged In",$prc[0];

$cnt =~ m/<b>(.*)\@gmail.com<\/b>/;

print "\nLogout $1?[n] : ";
$com=<STDIN>;chomp $com;
if($com eq "y")
{
logout;
goto RELOGIN;
}
else
{
return;
}
}

$cnt = $mech->response->as_string;
$cnt =~ s/\n|\s+/ /g;

printf("%-60.59s","Parsing for Login Page ");
#print $cnts;
if($cnt !~ m/id='liframe'.*?src='(.*)'/)
{
printf("%10s",$prc[1]);
print " Login page URL Not Found!\nTry Again OR Update the script! ".$prc[0];

return;
}

print $prc[2];
$url = $1;
$j=3;
REDO:
for($i=3;$i>=0;$i--)
{
printf("%-60.59s","GET $url");
$mech->get($url);
last if($mech->success());

printf("%10s",$prc[1]);
print " Retry (",$i,")".$prc[0] if($i);
}

return if($i<=0);

print $prc[2];

$cnt = $mech->response->as_string;
$cnt =~ s/\n|\s+/ /g;

$mech->form_number(1);
$mech->field("Email",$email."\@gmail.com");
$mech->field("Passwd",$pass);


printf("%-60.59s","Logging In ... ");

$mech->click("null");

$j--;
if($j && !$mech->success())
{
printf("%10s\n",$prc[1]);
goto REDO;
}
return unless($j);

$cnt = $mech->response->as_string;
$cnt =~ s/\n|\s+/ /g;

if(!$mech->find_link(text => "click here to continue"))
{
printf("%10s",$prc[1]);
print "\nWrong Usename or Password!",$prc[0];
return;
}


print $prc[2];
for($i=3;$i>=0;$i--)
{
printf("%-60.59s","Continuing ...");
$mech->follow_link(text => "click here to continue");
last if($mech->success());

printf("%10s",$prc[1]);
print " Retry (",$i,")".$prc[0] if($i);
}

return if($i<=0);

print $prc[2];

printf("%-60s","Parsing REDIRECT URL");
$cnt = $mech->response->as_string;
$cnt =~ s/\n|\s+/ /g;

if($cnt !~ m/location.replace\("(.*)"\)/)
{
printf("%10s",$prc[1]);
print "\nRedirect script missing!",$prc[0];
return;
}

$url = $1;
$url =~ s/\\u003d/=/g;

print $prc[2];
for($i=3;$i>=0;$i--)
{
printf("%-60.59s","GET $url");
$mech->get($url);
last if($mech->success());

printf("%10s",$prc[1]);
print " Retry (",$i,")".$prc[0] if($i);
}
return if($i<=0);

print $prc[2];
print "Logged In!";

#for($i=3; $i>=0;$i--)
#{
# printf("\n%-60s","GET /Home.aspx");
# $mech->get("http://www.orkut.com/Home.aspx");
# last if($mech->success());
#
# printf("%10s",$prc[1]);
# print " Retry (",$i,")".$prc[0] if($i);
#}

#return if($i<=0);
#print $prc[2];

}

sub logout
{

printf("%-60s","Parsing Logout");
if(!$mech->find_link(text => "Logout"))
{
printf("%10s",$prc[1]);
print "\nNot Logged In?",$prc[0];
return;
}


print $prc[2];
for($i=3;$i>=0;$i--)
{
printf("%-60.59s","Logging Out ...");
$mech->follow_link(text => "Logout");
last if($mech->success());

printf("%10s",$prc[1]);
print " Retry (",$i,")".$prc[0] if($i);
}
return if($i<=0);

print $prc[2];
}

sub home
{
REHOME:
for($i=3; $i>=0;$i--)
{
printf("%-60s","GET /Home.aspx");
$mech->get("http://www.orkut.com/Home.aspx");
last if($mech->success());

printf("%10s",$prc[1]);
print " Retry (",$i,")".$prc[0] if($i);
}

if($i<=0)
{
print $mech->response->as_string;
return;
}
print $prc[2];

if($mech->title !~ m/orkut.*home/i)
{

print $mech->response->as_string;
print "Not Logged In!",$prc[0];
print "\nLogin? [y] : ";
$com=<STDIN>;chomp $com;
if(not($com eq "n"))
{
login;
goto REHOME;
}
else
{
return;
}
}

#$mech->save_content("home.html");

$cnt = $mech->response->as_string;
$cnt =~ s/\n|\s+/ /g;
if($cnt =~ m/You are connected to <b>(.*)<\/b> people through <b>(.*)<\/b> friends./){
printf("\n%-20s: %0s (%0s)","Friends",$2,$1);}

if($cnt =~ m/([0-9]+) fans/){
printf("\n%-20s: %0s","Fans",$1);}

if($cnt =~ m/<b>([0-9]+)<\/b> scraps/i){
printf("\n%-20s: %0s","Scraps",$1);}

$cnt =~ m/my friends/g;
print "\nRecent : ";
while($cnt =~ m/Profile\.aspx\?uid=(.*?)">(<b>)*([^<]+)(<\/b>)*<\/a>/g)
{
print "\n\t$3";
}
}

sub grab_community
{
$comid = shift;
unless($file = shift)
{
print "\nFile to store : ";
$file = <STDIN>;
chomp $file;
}

$url = "/CommMembers.aspx?cmm=$comid";


for($i=3; $i>=0;$i--)
{
printf("%-60s","GET $url");
$mech->get("http://www.orkut.com$url");
last if($mech->success());

printf("%10s",$prc[1]);
print " Retry (",$i,")".$prc[0] if($i);
}

return 0 if($i<=0);
print $prc[2];

if($mech->title !~ m/orkut.*Community.*Members/)
{
print "Unexpected Page ! : ",$mech->title;
return 0;
}


$cnt = $mech->response->as_string;
#$cnt =~ m/showing <b>1-15<\/b> of (.*?)<\/b>/g;
#print " $1";

open APP,">$file";
$grabed=0;
printf("%-25s","Grabbed: $grabed ");
for($page=2;;$page++)
{
while($cnt =~ m/Profile\.aspx\?uid=(.*?)">(<b>)*([^<]+)(<\/b>)*<\/a>/g)
{
$grabed++;
print APP "\n$1>$3";
}
print "\e[25D";
printf("%-25s","Grabbed: $grabed ");
sleep(3);
if($mech->find_link(text_regex => qr/next/i))
{
$mech->follow_link(text_regex => qr/next/i);
}
else
{
last;
}

last if(!$mech->success());

$cnt = $mech->response->as_string;
}
print "\nSaved to \"$file\"".$prc[0];
close APP;
return $grabed;
}

sub grab_flist
{

$comid = shift;
unless($file = shift)
{
print "\nFile to store : ";
$file = <STDIN>;
chomp $file;
}

$url = "/FriendsList.aspx?uid=$comid";


for($i=3; $i>=0;$i--)
{
printf("%-60s","GET $url");
$mech->get("http://www.orkut.com$url");
last if($mech->success());

printf("%10s",$prc[1]);
print " Retry (",$i,")".$prc[0] if($i);
}

return 0 if($i<=0);
print $prc[2];

if($mech->title !~ m/orkut - (.*) Friends/)
{
print "Unexpected Page ! : ",$mech->title;
return 0;
}

print "$1 Friends : ".$prc[0];
$cnt = $mech->response->as_string;
#$cnt =~ m/showing <b>1-15<\/b> of (.*?)<\/b>/g;
#print " $1";

#$file =~ s/>//;
open APP,">$file";
$grabed=0;
printf("%-25s","Grabbed: $grabed ");
for($page=2;;$page++)
{
$cnt =~ m/Profile\.aspx\?uid=(.*?)">(<b>)*([^<]+)(<\/b>)*<\/a>/g;
while($cnt =~ m/Profile\.aspx\?uid=(.*?)">(<b>)*([^<]+)(<\/b>)*<\/a>/g)
{
$grabed++;
print APP "\n$1>$3";
}
print "\e[25D";
printf("%-25s","Grabbed: $grabed ");
sleep(3);
if($mech->find_link(text=> $page))
{
$mech->follow_link(text => $page);
}
else
{
last;
}

last if(!$mech->success());

$cnt = $mech->response->as_string;
}
print "\nSaved to \"$file\"".$prc[0];
close APP;
return $grabed;
}

sub grab_wild
{
$limit = shift;
$got = 0;
my $file;

unless($file=shift)
{
print "\nFile to store : ";
$file = <STDIN>;
chomp $file;
}


print "\nCommunity ID : ";
$comid = <STDIN>;chomp $comid;


open APP4, ">>$file";
print APP4 "\n<comment>CommMem $comid</comment>";
close APP4;

if($comid)
{
$got = grab_community($comid,">$file");
}
else
{
print "\nFriend ID : ";
$comid=<STDIN>;chomp $comid;
print $comid;
return 0 unless($comid);

open APP3, ">>$file";
print APP3 "\n<comment>FriendOf $comid</comment>";
close APP3;

$got = grab_flist($comid,">$file");
}

return 0 unless($got);

$offset=0;
$visits=0;
RESPIDER:
$file =~ s/>//;
open DLL, "$file";
@uids = <DLL>;
close DLL;

$cnt = join("\n",@uids);
$cnt =~ s/<comment>.*?<\/comment>//g;
@uids = split(/\n/,$cnt);
@uids = @uids[$offset..$#uids];

foreach $userid (@uids)
{
if($userid =~ m/([0-9]+)>/)
{
$file =~ s/>//;
if(open APP2, ">>$file")
{
print APP2 "\n<comment>FriendOf $1</comment>";
close APP2;
}
else {print $!," $file";exit}

$got+= grab_flist($1,">$file");
$visits++;
print " Got $got ".$prc[0];
last if($limit < $got);
}
}
if($limit > $got)
{
$offset = $#uids + 1;
goto RESPIDER;
}
print "\n Spider Results : ".$prc[0];
printf("%-30s : %0s\n","Indexed",$got);
printf("%-30s : %0s\n","Spidered",$visits);
print " Tip : Dont forget to simplify the uid file ".$prc[0];
}

sub grab
{
shift;
$what = shift;
$where = shift;
$file = shift;
if(!($what && $where))
{

print "\nArguments missing".$prc[0];
return;
}
if(lc($what) eq "comm" || lc($what) eq "community") {grab_community($where,$file);}
elsif(lc($what) eq "flist" || lc($what) eq "friendlist") {grab_flist($where,$file);}
elsif(lc($what) eq "wild") {grab_wild($where,$file);}
}



sub process_uids
{
my $file;
unless($file=shift)
{
print "\nFile to read : ";
$file = <STDIN>;
chomp $file;
}

open DLL, "$file";
@uids = <DLL>;
close DLL;

$cnt = join("\n",@uids);
$cnt =~ s/<comment>.*?<\/comment>\n//g;
$cnt =~ s/[\n]+/>/g;
$cnt =~ s/>//;

%hc = split(/>/,$cnt);

$file .= ".s";
if($dest = shift) {$file=$dest;}

open DLL,">$file" or die("$!");

$inx=0;
foreach $key (sort keys %hc)
{
$val = $hc{$key};
$inx++;
printf("%6d %28s %0s\n",$inx,"$key","$val");
print DLL "$key>$val>";
}
close DLL;

}


sub proces
{
shift;
$what = shift;
$file = shift;
$extra = shift;
unless($what)
{
print "\nArguments missing".$prc[0];
return;
}

if(lc($what) eq "uids") {process_uids($file,$extra); }

}






sub scrap
{
shift;
$pat = shift;

unless($source=shift)
{
print "\nFile to read : ";
$source = <STDIN>;
chomp $source;
}

if(!open FILE,"$source")
{
print " File not found!".$prc[0];
return;
}
@contents = <FILE>;
close FILE;
chomp @contents;
$cnts = join("",@contents);

$cnts =~ s/<//g;

%hc = split(/>/,$cnts);
$no = 1;
$scrapall=0;
$sc_start=0;
$sc_end=0;
@fkeys=();

$pat = ".*" unless($pat);

foreach $key (sort keys %hc)
{
$val = $hc{$key};
if($val =~ m/$pat/i)
{
printf("%6d %28s %0s\n",$no,"$key","$val");
$no++;
push @fkeys, $key;
}
}

if($no==0)
{
print " Friend Not found !".$prc[0];
}

print "Enter Friend # : ";
$myc = <STDIN>;
chomp $myc;
#todos ...

if($myc =~ m/([0-9]+)-([0-9]+)/)
{
$scrapall=1;
$myc=$sc_start=$1;
$sc_end=$2;
}

if($myc > $no)
{
print "Invalid Response!!!".$prc[0];return;
}
print "Enter Scrap Text : ";
$sctext = <STDIN>;
$sctext =~ s/\\n/\n/g;
#PS: Please do not remove the following if you really like this .... :)
#Please post a link to my website http://digitalpbk.blogspot.com
#thank you :)
$sctext = $sctext."\n[red](Powered by [blue]digitalpbk[/blue].blogspot.com)";
chomp $sctext;

SCRAPNEXT:
$friendid = $fkeys[$myc-1];

print " Scrapping $myc $friendid [$hc{$friendid}]".$prc[0];
sleep(4);
$url = "/Scrapbook.aspx?uid=$friendid";


for($i=3; $i>=0;$i--)
{
printf("%-60s","GET $url");
$mech->get("http://www.orkut.com$url");
last if($mech->success());

printf("%10s",$prc[1]);
print " Retry (",$i,")".$prc[0] if($i);
}


return 0 if($i<=0);
print $prc[2];

$cnt= $mech->response->as_string;
$cnt =~ s/\n|\s+/ /g;

if(($mech->title()) =~ m/orkut.*login/i)
{

print "Not Logged In!",$prc[0];
print "\nLogin? [y] : ";
$com=<STDIN>;chomp $com;
if(not($com eq "n"))
{
login;
goto SCRAPNEXT;
}
else
{
return;
}

sleep(3);
goto SCRAPNEXT;
}


if($cnt =~ m/"POST_TOKEN" value="(.*?)"/){
$post_token = $1;}

#print $post_token," ";
if($cnt =~ m/"signature" value="(.*?)"/){
$signature=$1;}
#print $signature;
sleep(3);
for($i=3;$i>=0;$i--)
{
printf( "%-60s","POST scrap");

#$mech->agent_alias("Linux Mozilla");
$mech->request(POST "http://www.orkut.com$url",["POST_TOKEN"=>$post_token,"signature"=>$signature,"scrapText"=>$sctext,"Action.writeScrapBasic"=>"Submit+Query"]);
last if($mech->success());

printf("%10s",$prc[1]);
print " Retry (",$i,")".$prc[0] if($i);
}

return 0 if($i<=0);
print $prc[2];

if($scrapall && $myc < $sc_end)
{
$myc++;
goto SCRAPNEXT;
}
print " Done.".$prc[0];
}

sub populate
{

shift;
$pat = shift;

unless($source=shift)
{
print "\nFile to read : ";
$source = <STDIN>;
chomp $source;
}

if(!open FILE,"$source")
{
print " File not found!".$prc[0];
return;
}
@contents = <FILE>;
close FILE;
chomp @contents;
$cnts = join("",@contents);

$cnts =~ s/<//g;

%hc = split(/>/,$cnts);
$no = 1;
$scrapall=0;
$sc_start=0;
$sc_end=0;
@fkeys=();

$pat = ".*" unless($pat);

foreach $key (sort keys %hc)
{
$val = $hc{$key};
if($val =~ m/$pat/i)
{
printf("%6d %28s %0s\n",$no,"$key","$val");
$no++;
push @fkeys, $key;
}
}

if($no==0)
{
print " Friend Not found !".$prc[0];
}

print "Enter Friend # : ";

$myc = <STDIN>;
chomp $myc;
#todos ...

if($myc =~ m/([0-9]+)-([0-9]+)/)
{
$scrapall=1;
$myc=$sc_start=$1;
$sc_end=$2;
}

if($myc > $no)
{
print "Invalid Response!!!".$prc[0];return;
}

ADDNEXT:
$friendid = $fkeys[$myc-1];

print " Adding $myc $friendid [$hc{$friendid}]".$prc[0];
sleep(4);
$url = "/FriendAdd.aspx?uid=$friendid";


for($i=3; $i>=0;$i--)
{
printf("%-60s","GET $url");
$mech->get("http://www.orkut.com$url");
last if($mech->success());

printf("%10s",$prc[1]);
print " Retry (",$i,")".$prc[0] if($i);
}


return 0 if($i<=0);
print $prc[2];

$cnt= $mech->response->as_string;
$cnt =~ s/\n|\s+/ /g;

if(($mech->title()) =~ m/orkut.*login/i)
{

print "Not Logged In!",$prc[0];
print "\nLogin? [y] : ";
$com=<STDIN>;chomp $com;
if(not($com eq "n"))
{
login;
goto ADDNEXT;
}
else
{
return;
}

sleep(3);
goto ADDNEXT;
}


if($cnt =~ m/"POST_TOKEN" value="(.*?)"/){
$post_token = $1;}

#print $post_token," ";
if($cnt =~ m/"signature" value="(.*?)"/){
$signature=$1;}
#print $signature;
sleep(3);
for($i=3;$i>=0;$i--)
{
printf( "%-60s","POST add");

#$mech->agent_alias("Linux Mozilla");
$mech->request(POST "http://www.orkut.com$url",["POST_TOKEN"=>$post_token,"signature"=>$signature,"level"=>"3","Action.yes"=>"Submit+Query"]);
last if($mech->success());

printf("%10s",$prc[1]);
print " Retry (",$i,")".$prc[0] if($i);
}

return 0 if($i<=0);
print $prc[2];

if($scrapall && $myc < $sc_end)
{
$myc++;
goto ADDNEXT;
}
print " Done.".$prc[0];



}


sub captchaget
{
$mech->request(GET "http://www.orkut.com/CaptchaImage.aspx");
open JPEG, ">captcha.jpg";

print JPEG $mech->response->content;
close JPEG;

}


Installing and Executing
To Install Copy the above full program. Paste it in a new text file and rename it as orkut.pl.
To Execute the program open a terminal / DOS Prompt and navigate to the folder where you have the orkut.pl.
Then type
perl orkut.pl


Getting Started
Once you execute the program you get a screen as follows

Command Line Orkut
By http://digitalpbk.blogspot.com
>


Quick Start Scrap all your friends

Command Line Orkut
By http://digitalpbk.blogspot.com
> login
> home
> grab flist [uid here Profile.aspx?uid=some numbers right? copy that numbers here]
Enter File : myfriends
> process uids myfriends
> scrap
Enter File : myfreinds.s
1
2
3
4
.
.
.
N
Enter Friend Number: 1-N
Enter Scrap text : This is coooool.




Avaliable commands
  • login: This command is used to Login into Orkut.com, you will have to enter a valid Username and Password to enter the site. If someone is already logged in the command asks your confirmation to logout that person and log you in or to continue with the existing.

    > login

    Gmail ID : example@example.com
    Password : Password

    GET /Home.aspx [ OK ]
    Parsing for Login Page [ OK ]
    GET https://www.google.com/accounts/ServiceLoginBox?service [ OK ]
    Logging In ... [ OK ]
    Continuing ... [ OK ]
    Parsing REDIRECT URL [ OK ]
    GET http://www.orkut.com/RedirLogin.aspx?msg=0&page=http%3A [ OK ]
    Logged In!



  • home: This command parses the Home.aspx file and gives you a summary of the page as shown below. If you are not logged in the command executes the login and continues if successful.

    > home
    GET /Home.aspx [ OK ]

    Friends : 291 (57,431,788)
    Fans : 138
    Scraps : 4
    Recent :
    abcd (305)
    xyz (391)
    def (151)
    I maybe wrong... (301)
    fghhh (376)
    someone (289)
    exmple (673)
    real (679)


    The number in brackets in friends indicate the total number of people in orkut.
    Recent shows the recently online friends on orkut. All others mean what they stand for.

  • grab what from [to] : Before you can start scrapping or do anything further, you must first build a database of friends or list of orkut id's. The Grab function is used to make the database. It takes two parameters and an optional third parameter:
    • what where: can take values [comm or community | flist or friendlist | wild ]

      comm or community : indicates that the list of friends is going to be grabbed from a community. In this case the from specifies a community id. (Community.aspx?cmm=ID)

      flist or friendlist: indicates that the list of friends is going to be from a friend's friends. In this case the from specifies the Orkut uid (FriendsList.aspx?uid=ID)

      wild : this is a combo of the above and grabs as much people specified by second parameter.

    • to : is an optional parameter that specifies the file to store the grabbed id's. If this parameter is left out, you will be asked to enter the file. If the file exists the new data is appended to the old file.


  • process uids : The grabbed ids by grab is not well formatted and may contain duplicates the process uids command formats the database and makes a final file. This command asks for the source file and makes a new destination file named by appending a .s extension to the original file. The formatted database is displayed.


  • scrap [filter] [source db] : is used to scrap multiple people. It takes 2 optional arguments.
    1. Filter : filters the source db according to the name. If skiped all persons in the database will be marked for scrapping.
    2. Source DB : The .s file that is required. If skiped you will be asked to enter location.


    > scrap just

    File to read : sample.id.s
    1 12312312313123123123 Just for keepin the communities
    Enter Friend # : 1
    Enter Scrap Text : hii \n how are you?
    Scrapping 1 12312312313123123123 [Just for keepin the communities]
    GET /Scrapbook.aspx?uid=12312312313123123123 [ OK ]
    POST scrap [FAILED] Retry (3)
    POST scrap [ OK ]
    Done.

    Enter Friend #: Takes a number or a format like X-X where X is a number. When X-X format is given all people between those two numbers will be marked for scrapping.

    Enter Scrap Text: The scrap text to be entered. To add new lines type \n and the scrap will have newlines when scrapped.

  • populate [Filter] [Source DB]: Same as scrap but this time its used to add the specified people as your friends.

  • captchaget : Just to read a Captcha and store the image as captcha.jpg



License
You are free to modify and edit by retaining a link or reference to this site.
There is no warranty what so ever. Any incidents of Orkut Banning you, or similar events shall not be my responsibility. Provided solely for education purpose. Any damage or inconvenience caused by the script is deeply regretted.
You have been warned.

Winding up...
I know this manual was too brief. I have tried as much to describe the Script. You will have confusions and doubts regarding the usage so please post your questions as a comment. I will be more than glad to answer them. If you really loved it or got it working or was helpful to you let me know. And dont forget to place a link to this page, if you are submitting to another site or forum.

Thanx Happy Orkutting...
:)

PS: If you noticed the Perl script colour coded, and like that check this out.