Showing posts with label wget. Show all posts
Showing posts with label wget. Show all posts

Wednesday, June 10, 2009

Mid-Week Neat Trick - With Proper Attribution

Hey there,

I actually have some stuff to write today, and was going to write it, but while I was trying to figure out an issue at work (that, strangely enough, had absolutely nothing to do with the topic of this post ;), I happened upon a great article, regarding novel uses of dd and text-based web tools like curl and wget, over at omnipotent.net's Linux article section

The trick it describes is one you may have heard of before, or put into practice, but I liked the author's enthusiasm for the subject matter (which comes through in the writing - along with many links to other interesting pieces) and thought I'd table my own meandering thoughts for a day and turn you on to someone else's ;)

I've included the introduction below. Follow this link, or the link at the end of this section, to continue reading. In fact, just click the link. All the really cool stuff follows the opener, although it sets up the mood quite nicely :)

Enjoy and cheers,



Surprisingly, I got quite a bit of response from my last piece, "Stupid Linux Tricks." That article was something I'd dashed off at the last second because I hadn't thought of anything provocative or rant-worthy to write about. Still, it seems to have hit an interesting chord with quite a few people. The idea that the best way to convert a person is to demonstrate some of the incredibly cool, useful, or just plain well-designed stuff about Linux. So, since I'm out of ideas this week too, I'll do something similar -- but instead concentrating on some of the smaller tools and what they can do.
Let's face it: Unix isn't a single, large product -- it's a fantastically modular system. It's so modular, in fact, that every component can in theory be replaced! So much so, that there is no single part of the Unix architecture that can, strictly speaking, be called Unix. The Linux kernel is just an implementation of an API, and an abstraction layer for hardware. That's not Unix. Neither are any of the potentially thousands of programs that make up Solaris, Linux, BSD, or any of the other ones. Any individual component is trivial, and is a part of a larger, cohesive whole.

Within that collective framework of tools, the user learns how to take advantage of them, one by one, learning how they interact and lock together, and their purposes and use. Often, a tool is used for purposes very unlike its intent. Almost frighteningly so, in fact. Very impressively so. Showing someone what these tools, few of which work as well as eye candy, can do to make your life easier is how you "clinch the sale" so to speak. So what if Linux can do all these cool things to impress people? Now you have to show them what it can do to make their lives easier in some small way... CONTINUE READING...




, Mike


Banner for College Student-Oriented Sites (728 version 1)



Please note that this blog accepts comments via email only. See our Mission And Policy Statement for further details.

Thursday, April 23, 2009

Beginning Modifications To Our Internet Mass Downloader For Linux And Unix

Hey there,

Today, we've got a little update (in need of some more updating) for those of you who like to scrape the web for pictures using our mass URL downloading Perl Script, or your own variation thereof. It should run on virtually any version or distro of Linux or Unix with Perl installed. If not, hopefully, it should only need minor modification.

NOTE: This update only addresses about 80% of the problems we've encountered. We'll post an update as soon as we figure out how to get around those ornery remaining 20% ;)

It seems that the folks at imagevenue (and other multimedia holding-tanks) have gotten around to changing the way they do their PHP redirects. Those are the annoying little scripts that open up a new window when you click on a hyperlink and then redirect you to another location which either contains the picture (or whatever) you want to download or (in some extreme cases) contain even more redirection. Of course, we don't blame them. What we're doing here, by breaking through all that nonsense to try and automate it in a Perl script, isn't unethical, but we understand that it might be a pain in the arse ;) And I'm sure (from what I see on download.com from time to time) that we're probably in the minority of people putting the hurt on them (and God bless them for still sticking around :)

This update is being presented in the form of a patch (If you need any help applying this one, check out this old post on using patch the easy way or, if you're familiar with "patch," just follow the simple prompts below to apply the attached patch below (created using "diff -c"). We've also included the same "dUpeDL" script that the Perl script calls (based on the findDupeFiles script by Cameron Hayne (macdev@hayne.net) - with full attribution and original headers included in the header of that fantastic "MD5 checksum + Size" duplicate checker).

In order to update your old version of "dUrl" (Check the above link if you need to download the latest version of the source), just download the original version (also, check out this post for some ideas about how to creatively download scripts from this blog; they sometimes cut and paste out as one continuous line!) and do the following (We're assuming your original script is called "dUrl" and our patch is called "dUrl.patch"):

host # cp dUrl dUrl.bak
host # wc -l *
325 dUrl
130 dUrl.patch
325 dUrl.bak
host # patch -p0 dUrl dUrl.patch
patching file dUrl

host # wc -l *;ls -l *
335 dUrl
325 dUrl.bak
130 dUrl.patch


Check the above link, also, for the easy way to back out the patch if you don't care for the mods. Also, once you're done, be sure to change all the "/home/mgolvach.." or "/users/..." paths that call the dUpeDL script to wherever you have that script located on your machine :)

Cheers,


Creative Commons License


This work is licensed under a
Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License


Begin Patch

*** dUrl Wed Apr 22 20:12:33 2009
--- dUrl.new Wed Apr 22 20:16:17 2009
***************
*** 1,7 ****
#!/usr/local/bin/perl

#
! # 2007 - Mike Golvach - eggi@comcast.net - beta v.000000000000000001a
#
# <a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/3.0/us/">Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License</a>
#
--- 1,7 ----
#!/usr/local/bin/perl

#
! # 2009 - Mike Golvach - eggi@comcast.net - beta v.000000000000000001b
#
# <a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/3.0/us/">Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License</a>
#
***************
*** 189,194 ****
--- 189,196 ----
foreach $multifile_entry (@multi_file) {
@dl_list=();
print "-------------------- FILE $counter ------------------------\n";
+ $phpcounter=1;
+ $phpurl = $dl_req;
$url="$multifile_entry";
if ( $url !~ /^http:\/\//i ) {
print "Usage: $0 [URL|-f URL file]\n";
***************
*** 237,244 ****
}
}
if ( $dl_req =~ /php\?/ ) {
! $dl_req =~ s/\&/\\&/g;
! system("wget -q $dl_req");
} else {
system("wget -q $dl_req");
}
--- 239,255 ----
}
}
if ( $dl_req =~ /php\?/ ) {
! if ( $dl_req =~ /img.php/ ) {
! $phpender = $dl_req;
! $phpstarter = $dl_req;
! $phpstarter =~ s/^(http:\/\/[^\/]*\/).*$/$1/;
! $phpender =~ s/^.*image=(.*)$/$1/;
! $phpcontent = "${phpstarter}$phpender";
! system("wget -q $phpcontent");
! } else {
! $dl_req =~ s/\&/\\&/g;
! system("wget -q $dl_req");
! }
} else {
system("wget -q $dl_req");
}
***************
*** 251,268 ****
@file_list=`ls -1d *php*`;
$file_list=@file_list;
if ( $file_list ) {
! print "PHP Trick-Links Found. Attempting To Unravel...\n";
foreach $php_file (@file_list) {
chomp($php_file);
open(PHPFILE, "<$php_file");
@php_file = <PHPFILE>;
! if ( $php_file =~ /img.php/ ) {
print "IMG - ";
foreach $php_seg (@php_file) {
if ( $php_seg =~ /SRC=/ ) {
$php_tail = $php_seg;
! $php_tail =~ s/.*SRC=\"(.*?)\">.*/$1/;
!
$php_real_url = $php_root . $php_tail;
} elsif ( $php_seg =~ /HREF=http/ ) {
$php_root = $php_seg;
--- 262,278 ----
@file_list=`ls -1d *php*`;
$file_list=@file_list;
if ( $file_list ) {
! print "PHP Trick-Links Found. Attempting To Unravel...\n";
foreach $php_file (@file_list) {
chomp($php_file);
open(PHPFILE, "<$php_file");
@php_file = <PHPFILE>;
! if ( $php_file =~ /img.php/ ) {
print "IMG - ";
foreach $php_seg (@php_file) {
if ( $php_seg =~ /SRC=/ ) {
$php_tail = $php_seg;
! $php_tail =~ s/.*SRC=\"([^\"]*)\".*/$1/;
$php_real_url = $php_root . $php_tail;
} elsif ( $php_seg =~ /HREF=http/ ) {
$php_root = $php_seg;
***************
*** 276,282 ****
foreach $php_seg (@php_file) {
if ( $php_seg =~ /url=http/ ) {
$php_real_url=$php_seg;
! $php_real_url =~ s/.*url=(http.*?)&.*/$1/;
}
}
}
--- 286,292 ----
foreach $php_seg (@php_file) {
if ( $php_seg =~ /url=http/ ) {
$php_real_url=$php_seg;
! $php_real_url =~ s/.*url=(http.*?\.[jgp][pin][gf]).*/$1/;
}
}
}
***************
*** 309,315 ****
chdir("$download_dir");
# Trying more sophisticated MD5 duplicate checking
print "Checking for exact duplicates MD5-Sum+Size\n";
! system("/users/mgolvach/bin/dUpeDL");
chdir("$this_dir");
$counter++;
}
--- 319,325 ----
chdir("$download_dir");
# Trying more sophisticated MD5 duplicate checking
print "Checking for exact duplicates MD5-Sum+Size\n";
! system("/export/home/users/dUpeDL");
chdir("$this_dir");
$counter++;
}



End Patch

---- dUpeDL - Based almost entirely on the findDupeFiles script by Cameron Hayne (macdev@hayne.net)

#!/usr/local/bin/perl

#
# dUpeDL - Based on the following script - only slightly modified to work with dURL
# Below: The original liner notes for full attribution to the original author.
#
# findDupeFiles:
# This script attempts to identify which files might be duplicates.
# It searches specified directories for files with a given suffix
# and reports on files that have the same MD5 digest.
# The suffix or suffixes to be searched for are specified by the first
# command-line argument - each suffix separated from the next by a vertical bar.
# The subsequent command-line arguments specify the directories to be searched.
# If no directories are specified on the command-line,
# it searches the current directory.
# Files whose names start with "._" are ignored.
#
# Cameron Hayne (macdev@hayne.net) January 2006 (revised March 2006)
#
#
# Examples of use:
# ----------------
# findDupeFiles '.aif|.aiff' AAA BBB CCC
# would look for duplicates among all the files with ".aif" or ".aiff" suffixes
# under the directories AAA, BBB, and CCC
#
# findDupeFiles '.aif|.aiff'
# would look for duplicates among all the files with ".aif" or ".aiff" suffixes
# under the current directory
#
# findDupeFiles '' AAA BBB CCC
# would look for duplicates among all the files (no matter what suffix)
# under the directories AAA, BBB, and CCC
#
# findDupeFiles
# would look for duplicates among all the files (no matter what suffix)
# under the current directory
# -----------------------------------------------------------------------------

use strict;
use warnings;

use File::Find;
use File::stat;
use Digest::MD5;
use Fcntl;

#REMOVE WHEN WE MERGE - UNNECESSARY
my $debug=0;

my $matchSomeSuffix;
if (defined($ARGV[0])) {
my @suffixes = split(/\|/, $ARGV[0]);
if (scalar(@suffixes) > 0) {
my $matchExpr = join('||', map {"m/\$suffixes[$_]\$/io"} 0..$#suffixes);
$matchSomeSuffix = eval "sub {$matchExpr}";
}
shift @ARGV;
}

my @searchDirs = @ARGV ? @ARGV : ".";
foreach my $dir (@searchDirs) {
die "\"$dir\" is not a directory\n" unless -d "$dir";
}
my %filesByDataLength;

sub calcMd5($) {

my ($filename) = @_;
if (-d $filename) {
return "unsupported";
}
sysopen(FILE, $filename, O_RDONLY) or die "Unable to open file \"$filename\": $!\n";
binmode(FILE);
my $md5 = Digest::MD5->new->addfile(*FILE)->hexdigest;
close(FILE);
return $md5;
}

sub hashByMd5($) {

my ($fileInfoListRef) = @_;
my %filesByMd5;
foreach my $fileInfo (@{$fileInfoListRef}) {
my $dirname = $fileInfo->{dirname};
my $filename = $fileInfo->{filename};
my $md5 = calcMd5("$dirname/$filename");
push(@{$filesByMd5{$md5}}, $fileInfo);
}
return \%filesByMd5;
}

sub checkFile() {

return unless -f $_;
my $filename = $_;
my $dirname = $File::Find::dir;
return if $filename =~ /^\._/;
if (defined($matchSomeSuffix)) {
return unless &$matchSomeSuffix;
}
my $statInfo = stat($filename) or warn "Can't stat file \"$dirname/$filename\": $!\n" and return;
my $size = $statInfo->size;
my $fileInfo = { 'dirname' => $dirname,
'filename' => $filename,
};
push(@{$filesByDataLength{$size}}, $fileInfo);
}

MAIN: {

find(\&checkFile, @searchDirs);
my $numDupes = 0;
my $numDupeBytes = 0;
if ( $debug ) {
print "Dupe Checking\n";
} else {
print "Dupe Checking - ";
}
foreach my $size (sort {$b<=>$a} keys %filesByDataLength) {
my $numSameSize = scalar(@{$filesByDataLength{$size}});
next unless $numSameSize > 1;
if ( $debug ) {
print "size: $size numSameSize: $numSameSize\n";
}
my $filesByMd5Ref = hashByMd5($filesByDataLength{$size});
my %filesByMd5 = %{$filesByMd5Ref};
foreach my $md5 (keys %filesByMd5) {
my @sameMd5List = @{$filesByMd5{$md5}};
my $numSameMd5 = scalar(@sameMd5List);
next unless $numSameMd5 > 1;
my $rsrcMd5;
my $dupe_counter=0;
foreach my $fileInfo (@sameMd5List) {
my $dirname = $fileInfo->{dirname};
my $filename = $fileInfo->{filename};
my $filepath = "$dirname/$filename";
if ( $dupe_counter == 0 ) {
if ( $debug ) {
print "KEEPING $filepath - MD5 $md5\n";
}
$dupe_counter++;
} else {
if ( $debug ) {
print "DELETING $filepath - MD5 $md5\n";
} else {
print "D";
}
unlink("$filepath");
}
}
if ( $debug) {
print "----------\n";
}
$numDupes += ($numSameMd5 - 1);
$numDupeBytes += ($size * ($numSameMd5 - 1));
}
}
print "----------\n";
my $numDupeMegabytes = sprintf("%.1f", $numDupeBytes / (1024 * 1024));
print "Number of duplicate files: $numDupes\n";
print "Estimated Mb Savings: $numDupeMegabytes\n";
}


, Mike




Discover the Free Ebook that shows you how to make 100% commissions on ClickBank!



Please note that this blog accepts comments via email only. See our Mission And Policy Statement for further details.

Tuesday, January 6, 2009

Using Wget's User Agent Option Safely On Linux And Unix

Hey there,

Today's post is a follow up to some questions we've received about our previously posted scripts designed to allow you to find your search index rank on Google, Yahoo, MSN/Live and Ask.com. If you read any of those posts (our even skimmed through to get to the script at the bottom of the box ;) you've probably noticed this glaring WARNING message that we feel compelled to attach to all of these posts (except for when we fixed the Yahoo script and forgot to re-include the warning, which was corrected immediately when a helpful reader pointed out that we did just that ...or we didn't do just that ...you understand what I'm getting at better than I can write it ;)

IMPORTANT NOTE: Although this warning is on the original Google search rank index page, it bears repeating here and now. If you use wget (as we are in this script), or any CLI web-browsing/webpage-grabbing software, and want to fake the User-Agent, please be careful. Please check this online article regarding the likelihood that you may be sued if you masquerade as Mozilla.

The above is a valid concern, which is why we include it on so many pages. We don't personally know anyone whom Mozilla has stomped upon and ground into dust, but they have made the fact that they are willing to do so, very well known. This posed a bit of a conundrum, considering that browsers ranging from Firefox to Opera to every version of Internet Explorer we can remember, all have the string "Mozilla" in their "user agent" identifier, or are otherwise linked to this gargantuan beast ;) This coincidence probably has to do with standards compliance and Internet ethics (some way they can make sure that people who hit a web page with IE get served up the same content as folks who hit that same page with Firefox), which (if you recall) Microsoft has a long and storied history of ignoring, while simultaneously "convincing" the majority of Internet sites and online businesses to "do it their way" by offering simple incentives, like free Development tools, as long as the end-user agreed not to support a competitor. They "almost" got in a whole bunch of trouble in the mid-late 90's when they started strong-arming ISP's into removing Netscape Navigator (which was, at the time, one of the most popular web browsers in use) from their installation CD's and begin packaging their startup-kits with IE instead. Remember; at that point in time, IE was about the biggest piece of garbage you could conceive of using to trudge your way through the web. Whether it still is remains debatable :)

In any event, as we looked around for a suitable replacement for the current "--user-agent=" setting in our scripts, we started to notice that Firefox and Mozilla were teaming up to join forces for such and such, and even browsers like Opera where forming alliances with Mozilla and MS. The question of what user agent is safe to use, per Mozilla's sue-first-ask-questions-later policy, became more and more confusing. We know for a fact that if we just use the default of "Wget/Version-Number," all four search engines will drop us like a bad habit on our first query. Finally, we happened upon a user agent that seemed to have no apparent (or, at least, overt) alliances or connections with Mozilla: Konqueror.

For Lynx fans out there, you can use that, too, but we get mixed results when testing with it since (even though it's been around since I can remember) lots of sites consider it a bot or spider and bump it. Plus, depending upon where you live you might get in some trouble ;)

And, before you start thinking: "Konqueror? Isn't that the scrappy little POS that KDE uses as a filesystem-viewer/web-browser?", we urge you to consider that the user agent we pick to run wget queries with doesn't need to have a great looking interface. As long as it can download a web page, from wget's perspective, Konqueror is exactly equal with the finest and most graphically-beautiful web-renderers out there. Basically, it can process HTML and doesn't appear to be on the sh##-list with Mozilla ;)

Below are a couple of suggestions for replacing the user-agent portion of our Google, Yahoo, MSN/Live and Ask.com search index ranking scripts so that you can stay out of trouble and keep tabs on your SEO (or whatever other things you may be doing that are none of our business whatsoever ;).

We ask that you make these changes for your own personal security and to keep history from showing again and again how nature points out the folly of men: Mozilla! ;)

1. Simply replace "--user-agent=Firefox" with "--user-agent=Konqueror"

2. Set this option up in your .wgetrc so you never have to think about it again and can, consequently, shorten the length of all four of these scripts:

user_agent = Konqueror

3. Or, alternately, set it as an alias in your environment:

host # alias wget='wget --user-agent=Konqueror'

Of course, for all of these, if you still have issues with getting dumped too early by the search engines (we put in the random 0-60 second wait time between queries to try and not upset them too much), you can try using these other options with wget. None of these come with any warning attached that we're aware of:

--referer="http://www.pick-a-site.com" <-- This can come in handy if you're dealing with a site that will give you a different page if you go directly to the URL, rather than going to it through a specific referring URL.

--header="Accept-Encoding: gzip,deflate" <-- Don't use this unless you're sure that you can handle compressed data. If you start getting garbage back, take this option out first. This option should work find on most Linux and Unix distro's right out of the box.

--header="Keep-Alive: 300" <-- Not really necessary, but might help you when a search engine (like, say, Yahoo) tends to notice multiple single-shot queries from the same IP. This will establish some semblance of a session, allowing you to send multiple requests through one sustained connection, although it probably won't fool them for long. Just as long as it fools them long enough ;)

Here are those options as they would appear in your .wgetrc:

referer = http://www.pick-a-site.com
header = Accept-Encoding: gzip,deflate
header = Keep-Alive: 300


and, in an alias, which is exactly like typing the command, except you shouldn't have to ever do it again for your entire login session (or for even longer, if you include it in your proper .profile, .bashrc, etc, login initialization file):

alias wget='wget --referer="http://www.pick-a-site.com" --header="Accept-Encoding: gzip,deflate" --header="Keep-Alive: 300"'

We'll be sure and post updated data as we get a chance to test and see how long we can keep Yahoo going before they bounce us (if it hasn't already been reduced to 1 hit by a Yahoo employee who can't stand this blog ;)

Cheers,

, Mike


Discover the ClickBank affiliate program that pays 100% commission!



Please note that this blog accepts comments via email only. See our Mission And Policy Statement for further details.

Wednesday, October 29, 2008

Pulling Info From IMDB Part One: Goofy Movie Titles

Hey There,

We're going off the range here today (while we leave another script on the oven to simmer for 24 hours ;) and moving along to finding the best way to strip "random-yet-connected" data from any online source.

The script should be fully tested by tomorrow, but for today we'll just be showing you what we've gotten it to produce so far (since it had to be manually massaged a bit).

This "project" will accomplish two simultaneous goals; neither of which will probably end up being for the betterment of mankind ;)

1. Scour the Internet Movie DataBase Main Search Hub-Page, using wget for Linux or Unix, and find all the movie titles that match our seed-pool of words or phrases.

2. Mix the real movie titles with fake movie titles culled from our seed-pool. For instance "Maximum Proposal" is a movie title created by combining two different members of our seed-pool. It's made up of two words which, when taken separately, appear in lots and lots of movie titles. Together, they're just completely ridiculous ;)

The result is, hopefully, as amusing for everyone else as it was (and is) for us :)

Cheers,



Stupid Movie Titles






Currently Reigning Champion


Baby Monitor: Sound of Fear






Presenting, in an ongoing attempt at maintaining alphabetical order, a collection of some of the worst and most uninspired creations of the military-industrial-entertainment complex.


Most are real, some I just made up.


If you can find all the fakes, treat yourself to a brand new couch!






(Yadda, Yadda, Yadda) Planet of the Apes


Afterthoughtfulness


Agony of Love: Lace and Lash


Ain't Love Cuckoo?


Aliens From Another Planet


Allergic to Love


Analysis of a Proposal


Analytical Instinct


Barn of the Blood Llama


Battle Taxi


Big Love - An Invitation to Disaster


Blood Arrow


Blood Church


Blood Diner


Blood Freak


Blood Kick: Kung Fu of the Five Hand Ninja


Blood Orgy of the She Devils


Blood Sucking Freaks


Blood and Donuts


Bloodsucking Pharoahs in Pittsburgh


Bloodthirsty Butchers


Bloody Hand Goddess


Bride of Chucky


Bride of the Monster


Brutal Carnage


Burning Sensation


Carpet Burn


Chased by Bloodhounds


Chronic Halitosis


Critical Motive


Cyberteens in Love


Dead Heat


Death By Dialogue


Death Car On the Freeway


Death Diploma


Death Fish


Death Goes To School


Death May Be Your Santa Claus


Death and the Compass


Decisive Impact


Deep Blood


Deep Fist


Deep Impact


Deep Rising


Deep Rub


Deep Sea Doodle


Devil Dog: The Hound of Hell


Double Impact


Dragonball


Drunk Driving


Dunston Checks In


Education High


Evil Mystery Friend


Evil Undead


Fatal Glimpse


Fatal Proposal


Fiduciary Responsibility


Final Debenture


Final Exam


Final Impact


Final Instigator


Final Instinct


Fist Fighter


Fistful of Fingers


Fistful of Fist


Forced Vengeance


Foxy By Proxy


Frank Proposal


Frankenstein: The College Years


Full Impact


Funky Monkey 2


Guilty as Hell


Gymkata


Happy Victim


Hard Impact


Headless Body in Topless Bar


Headless Eyes


Hollywood Chainsaw Hookers


I Know Where You Went Last Summer


Immediate Seizure


In Abstentia


Indecent Analysis


Indecent Impact


Insaniac


Instinctive Analysis


Instinctive Proposal


It's Alive III: Island of the Alive


It's Hummer Time


Judge the Bloody City


KickDancer


Kicked in the Face


Kiss The Blood Off My Hands


Kung Fu Master Named Drunk Cat


Let's Do Life


Leveraged Buyout


Liberal Helping


Live By the Fist


Living Bed of Blood


Lumbering Behemoth


Mad City


Maximum Analysis


Maximum Impact


Maximum Proposal


Maximum Risk


Maximum Surge


Mister Deathman


Mod F*** Explosion


Montgolfier of Death


Mr. Clean


My Friend, Flicka


My Giant


My Life As An Eggplant


My One Good Leg


Mystery Trellis


Night of the Bloody Transplant


Nolo Contendre


Petticoat Planet


Presumed Guilty


Psychomania


Punch and Judo


Quantum Deep


Reality Bites


Reefer Madness


Samurai Blood, Samurai Guts


Sensation Hunters


Sensitive Analysis


Sensitive Impact


Sensitive Instinct


Sensitive Proposal


Sensual Recluse


Sex, Blood and Mutilation


Shades of Love: Tangerine Taxi


Shoot Fighter


Sinister Overtones


Ski Lift to Death


Spencer: The Judas Goat


Steel Dawn


Stonestreet: Who Killed the Centerfold Model?


Street Gun


Street Justice


Streets of Rage


Sugar Mommies


Sugar and Plastic


Tap Daddy


Taxi Dancer


Taxi Girls


Taxi! Taxi!


Tech Support: Customers in Crisis!


Terminal Force


Terminal Impact


Terminal Justice


That Darn Cat


The Bloody Olive


The Camptown Suicide Club


The Drunken Shaolin Monkey


The Heavy Hand of Dr. Grubensteiner


The Hippy Dentist


The Last Few Minutes in the Life of Marty Birnbaum


The Lickerish Quartet


The Lift


The Psychedelics


The Sadist


The Schmoozer


The Secret Bloody Island


The Snapper


The Stone Fox


Three Men and a Chimp


Thundering Taxis


Triple Impact


Trust: Why Did You Kill Me?


Unmitigated Analysis


Violent Planet


Wacky Taxi


WaterWorld


What Price Taxi?


When A Stranger Calls


World of the Drunken Master


Would You Like Fries With That?


Young Pistols


Young Zombies


Zoomstone





, Mike




Please note that this blog accepts comments via email only. See our Mission And Policy Statement for further details.

Wednesday, July 30, 2008

The Thesaurus Shell Script - New And Improved!

Hey There,

Today's post is a follow up on a post we did just last week on creating an online Thesaurus using shell scripting. In it, we took an already existing Thesaurus script called thes.sh from gentoo.org and spiffed it up a little so that you could use multiple word queries and extract the suggestions the online Thesaurus would give you if it couldn't find a match for your word or phrase. Of course, sometimes it couldn't find a match for you and, also, had no suggestions... You can't win 'em all ;)

Thanks for this post's updated, and more platform-independent, script goes out to Fred Stephens (who's starting his own Linux revolution over at Linux Latitude) and (like so many other folks who, sometimes, prefer to remain nameless) his help in modifying this script so that it would also run correctly on a few more Linux and Unix distro's I didn't have access to, is greatly appreciated!

In an effort to make the script more portable as well, we used wget instead of lynx and took away the dependency on the html2text program by replacing that versatile (but not always available) software with a series of simple sed executions. This, of course, didn't work exactly the same (or "the same enough" ) on as many distro's as possible. Of course, I knew, when I wrote it, that I couldn't possibly test it on every available platform, so the possibility of it behaving differently on someone else's OS was always there (I think it always is and always will be). But, especially as time lumbers on, if we let hurdles like that slow us down, we'll all eventually accomplish less and less in direct opposite proportion to the amount of variety the computing industry offers us (which is growing more and more abundant as I type). Eventually, no one would ever write any sort of program, spark an original thought or attempt to improve and/or modify solutions unless they had a blank check from the government (or a giant conglomerate) to fund their every notion ;)

But that's one of the great things about the internet. Although I'll agree that (to a certain extent) it promotes seclusion and separation of physical entities from the "uncomfortable" prospect of having to physically interact with one another, the flipside of that coin is that the internet provides the world's largest forum for the free interchange and exchange of information and ideas and makes it possible for like-minded individuals to pool their efforts and ingenuity to produce more, and better, solutions to problems at a much snappier pace.

This rewrite addresses an issue with the one part of the script I just "knew" in my gut wouldn't port to some distro somewhere: the sed execution line. As I mentioned above, the free (licensed under the GPL) software html2text is a project that's had a lot of development hours put into it (actual releases and versions, etc ;), so it's obviously much much better at parsing out html and converting it to plain text than any series of sed commands I could ever string together on a given afternoon. Again, we chose to use sed in order to try and make this script accessible to users who couldn't get their hands on html2text (which also requires python), since sed comes standard on every Linux and Unix distro I know of (and has been around for a long time).

In any event, the script's been spruced up a bit and should run cleaner (The change isn't drastic, but it's definitely significant. If you noticed any garbage characters getting returned to you when you ran the original, this rewrite should, hopefully, fix that for you :)

Thanks, again, for your contribution, Fred :)

BTW, if you want to see sample output, there's a picture on the parent post about this Thesaurus shell script. I'm not jamming it in here again to try and keep this blog light (although, I see I've typed another novel already ;)

Cheers,


Creative Commons License


This work is licensed under a
Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License

#!/bin/bash
# Thesaurus - Find something original to say :)
# 2008 - Mike Golvach - eggi@comcast.net (modified slightly by Fred J. Stephens - fjs205@gmail.com)
# Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License
#
if [ $# -lt 1 ]
then
echo "Usage: $0 YourThesaurusTerm"
echo "May be two or more words separated by spaces"
echo "but only one definition per execution."
echo "Ex: $0 leader"
echo "Ex: $0 big name"
exit 1
fi
args="$@"
wget=/usr/bin/wget
if [ $# -gt 1 ]
then
args=`echo $args|sed 's/ /%20/g'`
fi
echo
$wget -nv -O - http://thesaurus.reference.com/search?q="$args" 2>&1|\
egrep -i 'Synonyms:|Definition:|No results found|Thesaurus suggestions:'|\
sed -e 's/<br \/>/\n/g' -e 's/<[^>]*>//g' -e 's/ / /g' -e 's/\(.\)$/\1\n/' -e 's/Would you.*$//' -e 's/\ / /g'

exit 0


, Mike

Thursday, July 24, 2008

Shell Script To Emulate A Thesaurus For Linux or Unix

Hey There,

Today's Linux/Unix bash shell script is for those of us who sometimes get lost for words. This happens to me at least a few times a day as I seem to talk, and type, way too much. Every now and again, I'll find myself facing a sentence that is not only redundant, but also seems to repeat its central message more than once ;) Sometimes redundancy is a good thing, though. If you've ever listened to an instructional or motivational speaker, you've probably noticed that a lot of them like to hit on the "rule of 3's" (sometimes 4's and 5's, with the annoyance factor increasing commensurate to the occurrence of repetition :) I, personally, try not to repeat myself ever (although, in writing about a thesaurus, I'm almost certainly doomed to some sort of meta-paradox).

One of the times a good thesaurus can come in handy is when you're faced with having to use similar words within a restricted amount of space and the resulting text seems stilted because of it. For instance, the sentence:

As good an idea as it may seem, it's generally not good to repeat the same word within a sentence.

With a little thought (or a handy reference) can be made much more palatable, and the redundancy can be made to appear to have disappeared:

As good an idea as it may seem, it's generally not desirable to repeat the same word within a sentence.

Our script today is based on an original script (call "thes") that can be found at Gentoo.org and, like that script, makes use of the Online Thesaurus at reference.com.

The major differences between our script today, and the equally helpful one posted on Gentoo.org are mainly rooted in the method. For instance, their script makes use of lynx and a program you may not have installed by default, called html2text. Ours, while still relying on the online component, uses wget and sed. We went with wget over lynx since it's partial-source dump option is a little more predictable than lynx's. That's not to say that there's anything wrong with lynx, just that it didn't suit our needs for this particular endeavour.

Another major difference between the two is that we decided to go ahead and throw in the "%20" space declaration so that you could submit multi-word queries to the script and get a response that you'd expect. Check out the picture below for a quick example of submitting a bad multi-word query, a good multi-word query, a bad single-word query and a good single-word query. If you can't see the picture, for whatever reason, the output is fairly simple. When you submit a bad query of any type (single or multi-word), you'll get back a "No results found" message and some suggestions. When you submit a query that matches something, you'll receive a varying number of definitions followed by a varying number of synonyms (and, yes, I'm not using the script while I write this ;)

Click the picture below to see it in full size:

Sample Thesaurus script output

As of the writing of this post, I have yet to figure out the "&whatever" suffix to the URL that will make the online Thesaurus return more than 10 results per page, so there's still some work to be done there. If you're so inclined, you can write in a quick check and recheck into the script. The addition to the URL that will start you at definition number 11 (instead of 1; the default) would be "&start=11" - So far, except for with very general words like "good," I've found that this hasn't been necessary, but it would be a cool improvement.

Here's to finding new ways to express yourself (politely ;)

Cheers,


Creative Commons License


This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License

#!/bin/bash

#
# Thesaurus - Find something original to say :)
#
# 2008 - Mike Golvach - eggi@comcast.net
#
# Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License
#

if [ $# -lt 1 ]
then
echo "Usage: $0 YourThesaurusTerm"
echo "May be two or more words separated"
echo "by spaces, but only one definition"
echo "per execution."
echo "Ex: $0 goodness"
echo "Ex: $0 goodness gracious"
exit 1
fi

args="$@"
wget=/usr/bin/wget

if [ $# -gt 1 ]
then
args=`echo $args|sed 's/ /%20/g'`
fi

echo
$wget -nv -O - http://thesaurus.reference.com/search?q="$args" 2>&1|egrep -i 'Synonyms:|Definition:|No results found|Thesaurus suggestions:'|sed -e 's/<br \/>/\n/g' -e 's/<[^>]*>//g' -e 's/ / /g' -e 's/\(.\)$/\1\n/' -e 's/Would you.*$//'

exit 0


, Mike

Tuesday, December 25, 2007

Website and URL Downloading Using ActiveState Perl for Windows

Merry Christmas:) Again, my apologies to those of you who don't observe the holiday.

Today's post (inlined scripts aside) will be nice and short. I'll leave it to you to refer to yesterday's post if you want more information, or commentary, regarding the basics of this script and how to use it, as it's almost exactly the same.

These are special versions of the dUrl and dUpeDL scripts that I've ported to use ActiveState's Perl for Windows. This comes in handy when you want to do some massive downloading and don't have access to a Linux or Solaris box.

Note that the one requirement of the original script, "wget," is also needed for this version of the script to work. You can download that for free at http://www.christopherlewis.com/WGet/default.htm. Also, again, note that you should modify the lines in dUrl that contain the dUpeDL script reference, as they indicate a fictitious location for it!

Enjoy the day off of work, the company of your family and/or friends and, hopefully, some much deserved peace and rest.

Cheers!


Creative Commons License


This work is licensed under a
Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License

#!c:\perl\bin\perl

#
# 2007 - Mike Golvach - eggi@comcast.net - beta v.000000000000000001a
#
# Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License
#

use LWP::Simple;

if ( $#ARGV < 0 ) {
print "Usage: $0 [URL|-f URL file]\n";
print "URL must be in http:// format - no https yet\n";
exit(1);
}

$debug=0;
$multi=0;
$counter=1;
# simple for now - better save-system later, maybe...
# also, we'll make the shared download system a function

if ( $ARGV[0] eq "-f" ) {
if ( ! -f $ARGV[1] ) {
print "Can't find URL file $ARGV[1]!\n";
exit(2);
}
$multi_file=$ARGV[1];
$multi=1;
chomp($download_dir="$ARGV[1]");
$download_dir =~ s/\//_/g;
$download_dir =~ s/\\/_/g;
if ( ! -d $download_dir ) {
system("mkdir $download_dir");
}
if ( ! -d $download_dir ) {
print "Can't make Download Directory ${download_dir}!\n";
print "Exiting...\n";
exit(2);
}
} else {
chomp($download_dir="$ARGV[0]");
if ( $download_dir !~ /^http:\/\//i ) {
print "Usage: $0 [URL|-f URL file]\n";
print "URL must be in http:// format - no https yet\n";
exit(1);
}
$download_dir =~ s/.*\/\/([^\/]*).*/$1/;
if ( ! -d $download_dir ) {
system("mkdir $download_dir");
}
if ( ! -d $download_dir ) {
print "Can't make Download Directory ${download_dir}!\n";
print "Exiting...\n";
exit(2);
}
}

if ( $multi == 0 ) {
@dl_list=();
$url="@ARGV";
chomp($url);
print "Parsing URL $url...\n";
$dl = get("$url");
@dl = split(/[><]/, $dl);
print "Feeding $url To The Machine...\n";
foreach $dl_item (@dl) {
next if ( $dl_item !~ /(href|img)/ );
next if ( $dl_item !~ /http:\/\// );
next if ( $dl_item !~ /(jpg|jpeg|gif|png)/ );
$dl_item =~ s/(a href|img src)=('|")//;
$dl_item =~ s/('|").*//;
push(@dl_list, $dl_item);
}
$is_it_worth_it = @dl_list;
if ( $is_it_worth_it == 0 ) {
print "No Image References found!\n";
print "No point in continuing...\n";
print "Moving $download_dir to ${download_dir}.empty...\n";
rename("$download_dir", "${download_dir}.empty");
exit(4);
}
print "Churning Out URL Requests...\n";
if ( $debug == 0 ) {
print "j=jpg g=gif p=png ?=guess\n";
}
chomp($this_dir=`cd`);
chdir("$download_dir");
$start_time=(time);
foreach $dl_req (@dl_list) {
$tmp_dl="";
$req_filename = $dl_req;
$req_filename =~ s/.*\///;
if ( $debug ) {
print "Grabbing $req_filename\n";
} else {
$file_ext = $req_filename;
$file_ext =~ s/.*(jpg|gif|png).*/$1/;
if ( $file_ext !~ /(jpg|gif|png)$/ ) {
print "\?";
} else {
$file_ext =~ s/^(\w).*/$1/;
print "$file_ext";
}
}
# Work that bastard extra hard if it's a PHP Trick-Link
if ( $dl_req =~ /php\?/ ) {
$dl_req =~ s/\&/\\&/g;
system("wget.exe -q $dl_req");
} else {
# We need wget.exe because the Simple GET can't follow trails
system("wget.exe -q $dl_req");
}
}
$end_time=(time);
$seconds = sprintf("%d", $end_time - $start_time);
print "...DONE in $seconds seconds!\n";
# PHP links are a pain -
print "Looking for PHP Trick-Links...\n";
chdir("$download_dir");
@file_list=`dir /B *php*`;
$file_list=@file_list;
if ( $file_list ) {
print "PHP Trick-Links Found. Attempting To Unravel...\n";
foreach $php_file (@file_list) {
chomp($php_file);
open(PHPFILE, "<$php_file");
@php_file = <PHPFILE>;
if ( $php_file =~ /img.php/ ) {
print "IMG - ";
foreach $php_seg (@php_file) {
if ( $php_seg =~ /SRC=/ ) {
$php_tail = $php_seg;
$php_tail =~ s/.*SRC=\"(.*?)\">.*/$1/;

$php_real_url = $php_root . $php_tail;
} elsif ( $php_seg =~ /HREF=http/ ) {
$php_root = $php_seg;
$php_root =~ s/.*=(http:\/\/[^\/]*\/).*/$1/;
chomp($php_root);
}
$php_real_url = $php_root . $php_tail;
}
} else {
print "REGULAR - ";
foreach $php_seg (@php_file) {
if ( $php_seg =~ /url=http/ ) {
$php_real_url=$php_seg;
$php_real_url =~ s/.*url=(http.*?)&.*/$1/;
}
}
}
close(PHPFILE);
if ( $debug ) {
print "Deleting Bogus Download: $php_file\n";
} else {
print "X=";
}
unlink("$php_file");
if ( $debug ) {
print "Downloading Real URL : $php_real_url";
} else {
$php_file_ext = $php_real_url;
$php_file_ext =~ s/.*(jpg|gif|png).*/$1/;
if ( $php_file_ext !~ /(jpg|gif|png)$/ ) {
print "\?";
} else {
$php_file_ext =~ s/^(\w).*/$1/;
chomp($php_file_ext);
print "$php_file_ext ";
}
}
system("wget.exe -q $php_real_url");
}
print "...Done!\n";
} else {
print "No PHP Trick-Links To Unravel... Good\n";
}
chdir("$download_dir");
# Trying more sophisticated MD5 duplicate checking
print "Checking for exact duplicates MD5-Sum+Size\n";
system("c:\\docume~1\\user\\desktop\\dUpeDL.pl");
chdir("$this_dir");
} elsif ( $multi == 1 ) {
open(MULTIFILE, "<$multi_file");
@multi_file = <MULTIFILE>;
close(MULTIFILE);
print "------------------- MULTIFILE MODE ------------------------\n";
foreach $multifile_entry (@multi_file) {
@dl_list=();
print "-------------------- FILE $counter ------------------------\n";
$url="$multifile_entry";
if ( $url !~ /^http:\/\//i ) {
print "Usage: $0 [URL|-f URL file]\n";
print "URL must be in http:// format - no https yet\n";
exit(1);
}
chomp($url);
print "Parsing URL $url...\n";
$dl = get("$url");
@dl = split(/[><]/, $dl);
print "Feeding $url To The Machine...\n";
foreach $dl_item (@dl) {
next if ( $dl_item !~ /(href|img)/ );
next if ( $dl_item !~ /http:\/\// );
next if ( $dl_item !~ /(jpg|jpeg|gif|png)/ );
$dl_item =~ s/(a href|img src)=('|")//;
$dl_item =~ s/('|").*//;
push(@dl_list, $dl_item);
}
$is_it_worth_it = @dl_list;
if ( $is_it_worth_it == 0 ) {
print "No Image References found!\n";
print "Trying next FILE\n";
}
print "Churning Out URL Requests...\n";
if ( $debug == 0 ) {
print "j=jpg g=gif p=png ?=guess\n";
}
chomp($this_dir=`cd`);
chdir("$download_dir");
$start_time=(time);
foreach $dl_req (@dl_list) {
$tmp_dl="";
$req_filename = $dl_req;
$req_filename =~ s/.*\///;
if ( $debug ) {
print "Grabbing $req_filename\n";
} else {
$file_ext = $req_filename;
$file_ext =~ s/.*(jpg|gif|png).*/$1/;
if ( $file_ext !~ /(jpg|gif|png)$/ ) {
print "\?";
} else {
$file_ext =~ s/^(\w).*/$1/;
print "$file_ext";
}
}
if ( $dl_req =~ /php\?/ ) {
$dl_req =~ s/\&/\\&/g;
system("wget.exe -q $dl_req");
} else {
system("wget.exe -q $dl_req");
}
}
$end_time=(time);
$seconds = sprintf("%d", $end_time - $start_time);
print "...DONE in $seconds seconds!\n";
print "Looking for PHP Trick-Links...\n";
chdir("$download_dir");
@file_list=`dir /B *php*`;
$file_list=@file_list;
if ( $file_list ) {
print "PHP Trick-Links Found. Attempting To Unravel...\n";
foreach $php_file (@file_list) {
chomp($php_file);
open(PHPFILE, "<$php_file");
@php_file = <PHPFILE>;
if ( $php_file =~ /img.php/ ) {
print "IMG - ";
foreach $php_seg (@php_file) {
if ( $php_seg =~ /SRC=/ ) {
$php_tail = $php_seg;
$php_tail =~ s/.*SRC=\"(.*?)\">.*/$1/;

$php_real_url = $php_root . $php_tail;
} elsif ( $php_seg =~ /HREF=http/ ) {
$php_root = $php_seg;
$php_root =~ s/.*=(http:\/\/[^\/]*\/).*/$1/;
chomp($php_root);
}
$php_real_url = $php_root . $php_tail;
}
} else {
print "REGULAR - ";
foreach $php_seg (@php_file) {
if ( $php_seg =~ /url=http/ ) {
$php_real_url=$php_seg;
$php_real_url =~ s/.*url=(http.*?)&.*/$1/;
}
}
}
close(PHPFILE);
if ( $debug ) {
print "Deleting Bogus Download: $php_file\n";
} else {
print "X=";
}
unlink("$php_file");
if ( $debug ) {
print "Downloading Real URL : $php_real_url";
} else {
$php_file_ext = $php_real_url;
$php_file_ext =~ s/.*(jpg|gif|png).*/$1/;
if ( $php_file_ext !~ /(jpg|gif|png)$/ ) {
print "\?";
} else {
$php_file_ext =~ s/^(\w).*/$1/;
chomp($php_file_ext);
print "$php_file_ext ";
}
}
system("wget.exe -v $php_real_url");
}
print "...Done!\n";
} else {
print "No PHP Trick-Links To Unravel... Good\n";
}
chdir("$download_dir");
# Trying more sophisticated MD5 duplicate checking
print "Checking for exact duplicates MD5-Sum+Size\n";
system("c:\\docume~1\\user\\desktop\\dUpeDL.pl");
chdir("$this_dir");
$counter++;
}
}

$|=1;

if ( $multi == 1 ) {
chdir("$this_dir");
rename("$multi_file", "${multi_file}.done");
}
exit(0);


---- dUpeDL - Based almost entirely on the findDupeFiles script by Cameron Hayne (macdev@hayne.net) - modified for win32

#!c:\perl\bin\perl

#
# dUpeDL - Based on the following script - only slightly modified to work with
# dUrl and Windows Perl.
# Below: The original liner notes for full attribution to the original author.
# Note that the attribution was taken verbatim from the Linux/Unix script and may not
# be entirely accurate due to the fact that this script is a win32 port.
#
# findDupeFiles:
# This script attempts to identify which files might be duplicates.
# It searches specified directories for files with a given suffix
# and reports on files that have the same MD5 digest.
# The suffix or suffixes to be searched for are specified by the first
# command-line argument - each suffix separated from the next by a vertical bar.
# The subsequent command-line arguments specify the directories to be searched.
# If no directories are specified on the command-line,
# it searches the current directory.
# Files whose names start with "._" are ignored.
#
# Cameron Hayne (macdev@hayne.net) January 2006 (revised March 2006)
#
#
# Examples of use:
# ----------------
# findDupeFiles '.aif|.aiff' AAA BBB CCC
# would look for duplicates among all the files with ".aif" or ".aiff" suffixes
# under the directories AAA, BBB, and CCC
#
# findDupeFiles '.aif|.aiff'
# would look for duplicates among all the files with ".aif" or ".aiff" suffixes
# under the current directory
#
# findDupeFiles '' AAA BBB CCC
# would look for duplicates among all the files (no matter what suffix)
# under the directories AAA, BBB, and CCC
#
# findDupeFiles
# would look for duplicates among all the files (no matter what suffix)
# under the current directory
# -----------------------------------------------------------------------------

use strict;
use warnings;

use File::Find;
use File::stat;
use Digest::MD5;
use Fcntl;

#REMOVE WHEN WE MERGE - UNNECESSARY
my $debug=0;

my $matchSomeSuffix;
if (defined($ARGV[0])) {
my @suffixes = split(/\|/, $ARGV[0]);
if (scalar(@suffixes) > 0) {
my $matchExpr = join('||', map {"m/\$suffixes[$_]\$/io"} 0..$#suffixes);
$matchSomeSuffix = eval "sub {$matchExpr}";
}
shift @ARGV;
}

my @searchDirs = @ARGV ? @ARGV : ".";
foreach my $dir (@searchDirs) {
die "\"$dir\" is not a directory\n" unless -d "$dir";
}
my %filesByDataLength;

sub calcMd5($) {

my ($filename) = @_;
if (-d $filename) {
return "unsupported";
}
sysopen(FILE, $filename, O_RDONLY) or die "Unable to open file \"$filename\": $!\n";
binmode(FILE);
my $md5 = Digest::MD5->new->addfile(*FILE)->hexdigest;
close(FILE);
return $md5;
}

sub hashByMd5($) {

my ($fileInfoListRef) = @_;
my %filesByMd5;
foreach my $fileInfo (@{$fileInfoListRef}) {
my $dirname = $fileInfo->{dirname};
my $filename = $fileInfo->{filename};
my $md5 = calcMd5("$dirname/$filename");
push(@{$filesByMd5{$md5}}, $fileInfo);
}
return \%filesByMd5;
}

sub checkFile() {

return unless -f $_;
my $filename = $_;
my $dirname = $File::Find::dir;
return if $filename =~ /^\._/;
if (defined($matchSomeSuffix)) {
return unless &$matchSomeSuffix;
}
my $statInfo = stat($filename) or warn "Can't stat file \"$dirname/$filename\": $!\n" and return;
my $size = $statInfo->size;
my $fileInfo = { 'dirname' => $dirname,
'filename' => $filename,
};
push(@{$filesByDataLength{$size}}, $fileInfo);
}

MAIN: {

find(\&checkFile, @searchDirs);
my $numDupes = 0;
my $numDupeBytes = 0;
if ( $debug ) {
print "Dupe Checking\n";
} else {
print "Dupe Checking - ";
}
foreach my $size (sort {$b<=>$a} keys %filesByDataLength) {
my $numSameSize = scalar(@{$filesByDataLength{$size}});
next unless $numSameSize > 1;
if ( $debug ) {
print "size: $size numSameSize: $numSameSize\n";
}
my $filesByMd5Ref = hashByMd5($filesByDataLength{$size});
my %filesByMd5 = %{$filesByMd5Ref};
foreach my $md5 (keys %filesByMd5) {
my @sameMd5List = @{$filesByMd5{$md5}};
my $numSameMd5 = scalar(@sameMd5List);
next unless $numSameMd5 > 1;
my $rsrcMd5;
my $dupe_counter=0;
foreach my $fileInfo (@sameMd5List) {
my $dirname = $fileInfo->{dirname};
my $filename = $fileInfo->{filename};
my $filepath = "$dirname/$filename";
if ( $dupe_counter == 0 ) {
if ( $debug ) {
print "KEEPING $filepath - MD5 $md5\n";
}
$dupe_counter++;
} else {
if ( $debug ) {
print "DELETING $filepath - MD5 $md5\n";
} else {
print "D";
}
unlink("$filepath");
}
}
if ( $debug) {
print "----------\n";
}
$numDupes += ($numSameMd5 - 1);
$numDupeBytes += ($size * ($numSameMd5 - 1));
}
}
print "----------\n";
my $numDupeMegabytes = sprintf("%.1f", $numDupeBytes / (1024 * 1024));
print "Number of duplicate files: $numDupes\n";
print "Estimated Mb Savings: $numDupeMegabytes\n";
}



, Mike




Monday, December 24, 2007

Mass URL Downloading Using Perl for Linux or Solaris

Hopefully everyone's Holidays are going well. For Christmas Eve (which many of you may not observe, but our family traditionally does), I've decided to put a script I'm currently working on at the gift table. Family heritage celebrates Christmas on the Eve, so this is actually on time. Since the other half of my family are traditionalists, we still open a few gifts on the regular Holiday. To that end, I've put together an interesting variation on this script (the same, but wholey different) for tomorrow's post.

I call the script below "dUrl" because I wrote it to download tons of URL's (Clever? No ;) I've actually used this script for business related purposes, with sections ripped out, as it does have its place in that environment. For the most part, though, I use it to do massive downloading of pictures, video, audio, etc. All the stuff that's totally unnecessary and, therefore, the most fun to pull down on a massive scale. It will basically take any page you feed it and rip all the content down, including those bothersome PHP redirects that everyone uses nowadays to discourage this sort of activity :)

Although I don't put any restrictions in the script (in the form of "requires" statements), this might not run on Perl versions lower than 5.6. Just a guess based on some other scripts I've had to upgrade that used a lot of the same elements. This script has also been personally tested on RedHat Linux 7.x up to AS5 and Sun Solaris 2.6 through 10. It should theoretically work on any machine that can make use of Perl, with some possible minor revisions to any system calls.

This script only requires that you have the LWP::Simple Perl module installed (and all of its required modules). I've found that the simplest way to set this all up (since the dependency tree can be humongous if you're working off of a plain-vanilla installation of Perl) is to use the CPAN module (If you don't have this already, download it and install it. It comes standard with even the barest of Perl installations, as far as I know - In a future post I'll go into the old-style method of downloading all the modules and building them using the Makefile.PL method). Generally, this should do it (except the first time you use it, at which point it will ask you a bunch of questions it pretty much already knows the answers to ;) :

perl -MCPAN -e shell

> install LWP::Simple


and let it ride. You'll probably have to answer "y" a lot.

The script is fairly simple to use. It runs in two different modes: Single and Multi File mode. In Single File mode (and I define "file," in this context, as a URL), it's invoked like this:

host # ./dUrl http://host.com/webpage.html

In Multi File mode, it's invoked much the same way, except the argument is a real file that contains a list of URL's, one per line, like so:

host # ./dUrl FILENAME
host # cat FILENAME
http://host.com/page1.html
http://host.com/page2.html
...


This is a project in progress (Working on getting my SourceForge/FreshMeat pages up) and there are several things to note. It currently:

- Does not support SSL. Only the http protocol will work with it.
- Has built in support for dealing with PHP redirects. These are a royal pain in the bottom and I'm probably going to make this an entirely separate script, or module, that this script will use. Currently, I'm dissecting and re-following links using temp file parsing. It works for most of the larger media-hosting providers, but is still too specific to work on "all" of them.
- This version only downloads images. Modify the $dl_item variable to get around this.
- Relies on "wget" for some of its functionality. This is due to the stage of infancy its in. See the beta version number for a good laugh ;)
- Is longer than it needs to be, for my own ease of debugging. Eventually, the duplication of typed text will be rolled up into loops.
- Contains some possibly curious liner notes ;)

And, finally, until I find a better solution (which may not be possible, because this one's pretty darned good), I incorporate a slightly modified version of the "findDupeFiles" script, written by Cameron Hayne (macdev@hayne.net). It is only modified to the degree that I needed to make it work as an add-on to my script. You can find the original version of the file at http://hayne.net/MacDev/Perl/findDupeFiles. Although he doesn't know it, Cameron's excellent MD5-based duplicate finding script has been invaluable in saving me lots of time. I originally just looked for duplicates and renamed them using a simple incrementing-number scheme (since I'm paranoid and assume that I might accidentally lose something unique, no matter how unlikely the case ;) I've included the modified version of Cameron's script in this post as well, giving him full attribution with regards to his script's original header comment section.

Note, also, that I've renamed his script dUpeDL, since it's not the pure version. Modify the lines in dUrl that contain that script name, as they indicate a fictitious location for it!

Happy Christmas Eve, everyone :) For those of you who don't observe the Holiday, again, just consider this a special post that showed up at an arbitrary time ;)


Creative Commons License


This work is licensed under a
Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License

#!/usr/local/bin/perl

#
# 2007 - Mike Golvach - eggi@comcast.net - beta v.000000000000000001a
#
# Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License
#


use LWP::Simple;

if ( $#ARGV < 0 ) {
print "Usage: $0 [URL|-f URL file]\n";
print "URL must be in http:// format - no https yet\n";
exit(1);
}

$debug=0;
$multi=0;
$counter=1;
# simple for now - better save-system later...
# also, we'll make the shared download system a function

if ( $ARGV[0] eq "-f" ) {
if ( ! -f $ARGV[1] ) {
print "Can't find URL file $ARGV[1]!\n";
exit(2);
}
$multi_file=$ARGV[1];
$multi=1;
chomp($download_dir="$ARGV[1]");
$download_dir =~ s/\//_/g;
if ( ! -d $download_dir ) {
system("mkdir $download_dir");
}
if ( ! -d $download_dir ) {
print "Can't make Download Directory ${download_dir}!\n";
print "Exiting...\n";
exit(2);
}
} else {
chomp($download_dir="$ARGV[0]");
if ( $download_dir !~ /^http:\/\//i ) {
print "Usage: $0 [URL|-f URL file]\n";
print "URL must be in http:// format - no https yet\n";
exit(1);
}
$download_dir =~ s/.*\/\/([^\/]*).*/$1/;
if ( ! -d $download_dir ) {
system("mkdir $download_dir");
}
if ( ! -d $download_dir ) {
print "Can't make Download Directory ${download_dir}!\n";
print "Exiting...\n";
exit(2);
}
}

if ( $multi == 0 ) {
@dl_list=();
$url="@ARGV";
chomp($url);
print "Parsing URL $url...\n";
$dl = get("$url");
@dl = split(/[><]/, $dl);
print "Feeding $url To The Machine...\n";
foreach $dl_item (@dl) {
next if ( $dl_item !~ /(href|img)/ );
next if ( $dl_item !~ /http:\/\// );
next if ( $dl_item !~ /(jpg|jpeg|gif|png)/ );
$dl_item =~ s/(a href|img src)=('|")//;
$dl_item =~ s/('|").*//;
push(@dl_list, $dl_item);
}
$is_it_worth_it = @dl_list;
if ( $is_it_worth_it == 0 ) {
print "No Image References found!\n";
print "No point in continuing...\n";
print "Moving $download_dir to ${download_dir}.empty...\n";
rename("$download_dir", "${download_dir}.empty");
exit(4);
}
print "Churning Out URL Requests...\n";
if ( $debug == 0 ) {
print "j=jpg g=gif p=png ?=guess\n";
}
chomp($this_dir=`pwd`);
chdir("$download_dir");
$start_time=(time);
foreach $dl_req (@dl_list) {
$tmp_dl="";
$req_filename = $dl_req;
$req_filename =~ s/.*\///;
if ( $debug ) {
print "Grabbing $req_filename\n";
} else {
$file_ext = $req_filename;
$file_ext =~ s/.*(jpg|gif|png).*/$1/;
if ( $file_ext !~ /(jpg|gif|png)$/ ) {
print "\?";
} else {
$file_ext =~ s/^(\w).*/$1/;
print "$file_ext";
}
}
# Work that bastard extra hard if it's a PHP Trick-Link
if ( $dl_req =~ /php\?/ ) {
$dl_req =~ s/\&/\\&/g;
system("wget -q $dl_req");
} else {
# We need wget because the Simple GET can't follow trails
system("wget -q $dl_req");
}
}
$end_time=(time);
$seconds = sprintf("%d", $end_time - $start_time);
print "...DONE in $seconds seconds!\n";
# PHP links are a pain -
print "Looking for PHP Trick-Links...\n";
chdir("$download_dir");
@file_list=`ls -1d *php*`;
$file_list=@file_list;
if ( $file_list ) {
print "PHP Trick-Links Found. Attempting To Unravel...\n";
foreach $php_file (@file_list) {
chomp($php_file);
open(PHPFILE, "<$php_file");
@php_file = <PHPFILE>;
if ( $php_file =~ /img.php/ ) {
print "IMG - ";
foreach $php_seg (@php_file) {
if ( $php_seg =~ /SRC=/ ) {
$php_tail = $php_seg;
$php_tail =~ s/.*SRC=\"(.*?)\">.*/$1/;

$php_real_url = $php_root . $php_tail;
} elsif ( $php_seg =~ /HREF=http/ ) {
$php_root = $php_seg;
$php_root =~ s/.*=(http:\/\/[^\/]*\/).*/$1/;
chomp($php_root);
}
$php_real_url = $php_root . $php_tail;
}
} else {
print "REGULAR - ";
foreach $php_seg (@php_file) {
if ( $php_seg =~ /url=http/ ) {
$php_real_url=$php_seg;
$php_real_url =~ s/.*url=(http.*?)&.*/$1/;
}
}
}
close(PHPFILE);
if ( $debug ) {
print "Deleting Bogus Download: $php_file\n";
} else {
print "X=";
}
unlink("$php_file");
if ( $debug ) {
print "Downloading Real URL : $php_real_url";
} else {
$php_file_ext = $php_real_url;
$php_file_ext =~ s/.*(jpg|gif|png).*/$1/;
if ( $php_file_ext !~ /(jpg|gif|png)$/ ) {
print "\?";
} else {
$php_file_ext =~ s/^(\w).*/$1/;
chomp($php_file_ext);
print "$php_file_ext ";
}
}
system("wget -q $php_real_url");
}
print "...Done!\n";
} else {
print "No PHP Trick-Links To Unravel... Good\n";
}
chdir("$download_dir");
# Trying more sophisticated MD5 duplicate checking
print "Checking for exact duplicates MD5-Sum+Size\n";
system("/export/home/users/dUpeDL");
chdir("$this_dir");
} elsif ( $multi == 1 ) {
open(MULTIFILE, "<$multi_file");
@multi_file = <MULTIFILE>;
close(MULTIFILE);
print "------------------- MULTIFILE MODE ------------------------\n";
foreach $multifile_entry (@multi_file) {
@dl_list=();
print "-------------------- FILE $counter ------------------------\n";
$url="$multifile_entry";
if ( $url !~ /^http:\/\//i ) {
print "Usage: $0 [URL|-f URL file]\n";
print "URL must be in http:// format - no https yet\n";
exit(1);
}
chomp($url);
print "Parsing URL $url...\n";
$dl = get("$url");
@dl = split(/[><]/, $dl);
print "Feeding $url To The Machine...\n";
foreach $dl_item (@dl) {
next if ( $dl_item !~ /(href|img)/ );
next if ( $dl_item !~ /http:\/\// );
next if ( $dl_item !~ /(jpg|jpeg|gif|png)/ );
$dl_item =~ s/(a href|img src)=('|")//;
$dl_item =~ s/('|").*//;
push(@dl_list, $dl_item);
}
$is_it_worth_it = @dl_list;
if ( $is_it_worth_it == 0 ) {
print "No Image References found!\n";
print "Trying next FILE\n";
}
print "Churning Out URL Requests...\n";
if ( $debug == 0 ) {
print "j=jpg g=gif p=png ?=guess\n";
}
chomp($this_dir=`pwd`);
chdir("$download_dir");
$start_time=(time);
foreach $dl_req (@dl_list) {
$tmp_dl="";
$req_filename = $dl_req;
$req_filename =~ s/.*\///;
if ( $debug ) {
print "Grabbing $req_filename\n";
} else {
$file_ext = $req_filename;
$file_ext =~ s/.*(jpg|gif|png).*/$1/;
if ( $file_ext !~ /(jpg|gif|png)$/ ) {
print "\?";
} else {
$file_ext =~ s/^(\w).*/$1/;
print "$file_ext";
}
}
if ( $dl_req =~ /php\?/ ) {
$dl_req =~ s/\&/\\&/g;
system("wget -q $dl_req");
} else {
system("wget -q $dl_req");
}
}
$end_time=(time);
$seconds = sprintf("%d", $end_time - $start_time);
print "...DONE in $seconds seconds!\n";
print "Looking for PHP Trick-Links...\n";
chdir("$download_dir");
@file_list=`ls -1d *php*`;
$file_list=@file_list;
if ( $file_list ) {
print "PHP Trick-Links Found. Attempting To Unravel...\n";
foreach $php_file (@file_list) {
chomp($php_file);
open(PHPFILE, "<$php_file");
@php_file = <PHPFILE>;
if ( $php_file =~ /img.php/ ) {
print "IMG - ";
foreach $php_seg (@php_file) {
if ( $php_seg =~ /SRC=/ ) {
$php_tail = $php_seg;
$php_tail =~ s/.*SRC=\"(.*?)\">.*/$1/;

$php_real_url = $php_root . $php_tail;
} elsif ( $php_seg =~ /HREF=http/ ) {
$php_root = $php_seg;
$php_root =~ s/.*=(http:\/\/[^\/]*\/).*/$1/;
chomp($php_root);
}
$php_real_url = $php_root . $php_tail;
}
} else {
print "REGULAR - ";
foreach $php_seg (@php_file) {
if ( $php_seg =~ /url=http/ ) {
$php_real_url=$php_seg;
$php_real_url =~ s/.*url=(http.*?)&.*/$1/;
}
}
}
close(PHPFILE);
if ( $debug ) {
print "Deleting Bogus Download: $php_file\n";
} else {
print "X=";
}
unlink("$php_file");
if ( $debug ) {
print "Downloading Real URL : $php_real_url";
} else {
$php_file_ext = $php_real_url;
$php_file_ext =~ s/.*(jpg|gif|png).*/$1/;
if ( $php_file_ext !~ /(jpg|gif|png)$/ ) {
print "\?";
} else {
$php_file_ext =~ s/^(\w).*/$1/;
chomp($php_file_ext);
print "$php_file_ext ";
}
}
system("wget -v $php_real_url");
}
print "...Done!\n";
} else {
print "No PHP Trick-Links To Unravel... Good\n";
}
chdir("$download_dir");
# Trying more sophisticated MD5 duplicate checking
print "Checking for exact duplicates MD5-Sum+Size\n";
system("/users/mgolvach/bin/dUpeDL");
chdir("$this_dir");
$counter++;
}
}

$|=1;

if ( $multi == 1 ) {
chdir("$this_dir");
rename("$multi_file", "${multi_file}.done");
system("tar cpf ${download_dir}.tar $download_dir");
}
exit(0);


---- dUpeDL - Based almost entirely on the findDupeFiles script by Cameron Hayne (macdev@hayne.net)

#!/usr/local/bin/perl

#
# dUpeDL - Based on the following script - only slightly modified to work with dURL
# Below: The original liner notes for full attribution to the original author.
#
# findDupeFiles:
# This script attempts to identify which files might be duplicates.
# It searches specified directories for files with a given suffix
# and reports on files that have the same MD5 digest.
# The suffix or suffixes to be searched for are specified by the first
# command-line argument - each suffix separated from the next by a vertical bar.
# The subsequent command-line arguments specify the directories to be searched.
# If no directories are specified on the command-line,
# it searches the current directory.
# Files whose names start with "._" are ignored.
#
# Cameron Hayne (macdev@hayne.net) January 2006 (revised March 2006)
#
#
# Examples of use:
# ----------------
# findDupeFiles '.aif|.aiff' AAA BBB CCC
# would look for duplicates among all the files with ".aif" or ".aiff" suffixes
# under the directories AAA, BBB, and CCC
#
# findDupeFiles '.aif|.aiff'
# would look for duplicates among all the files with ".aif" or ".aiff" suffixes
# under the current directory
#
# findDupeFiles '' AAA BBB CCC
# would look for duplicates among all the files (no matter what suffix)
# under the directories AAA, BBB, and CCC
#
# findDupeFiles
# would look for duplicates among all the files (no matter what suffix)
# under the current directory
# -----------------------------------------------------------------------------

use strict;
use warnings;

use File::Find;
use File::stat;
use Digest::MD5;
use Fcntl;

#REMOVE WHEN WE MERGE - UNNECESSARY
my $debug=0;

my $matchSomeSuffix;
if (defined($ARGV[0])) {
my @suffixes = split(/\|/, $ARGV[0]);
if (scalar(@suffixes) > 0) {
my $matchExpr = join('||', map {"m/\$suffixes[$_]\$/io"} 0..$#suffixes);
$matchSomeSuffix = eval "sub {$matchExpr}";
}
shift @ARGV;
}

my @searchDirs = @ARGV ? @ARGV : ".";
foreach my $dir (@searchDirs) {
die "\"$dir\" is not a directory\n" unless -d "$dir";
}
my %filesByDataLength;

sub calcMd5($) {

my ($filename) = @_;
if (-d $filename) {
return "unsupported";
}
sysopen(FILE, $filename, O_RDONLY) or die "Unable to open file \"$filename\": $!\n";
binmode(FILE);
my $md5 = Digest::MD5->new->addfile(*FILE)->hexdigest;
close(FILE);
return $md5;
}

sub hashByMd5($) {

my ($fileInfoListRef) = @_;
my %filesByMd5;
foreach my $fileInfo (@{$fileInfoListRef}) {
my $dirname = $fileInfo->{dirname};
my $filename = $fileInfo->{filename};
my $md5 = calcMd5("$dirname/$filename");
push(@{$filesByMd5{$md5}}, $fileInfo);
}
return \%filesByMd5;
}

sub checkFile() {

return unless -f $_;
my $filename = $_;
my $dirname = $File::Find::dir;
return if $filename =~ /^\._/;
if (defined($matchSomeSuffix)) {
return unless &$matchSomeSuffix;
}
my $statInfo = stat($filename) or warn "Can't stat file \"$dirname/$filename\": $!\n" and return;
my $size = $statInfo->size;
my $fileInfo = { 'dirname' => $dirname,
'filename' => $filename,
};
push(@{$filesByDataLength{$size}}, $fileInfo);
}

MAIN: {

find(\&checkFile, @searchDirs);
my $numDupes = 0;
my $numDupeBytes = 0;
if ( $debug ) {
print "Dupe Checking\n";
} else {
print "Dupe Checking - ";
}
foreach my $size (sort {$b<=>$a} keys %filesByDataLength) {
my $numSameSize = scalar(@{$filesByDataLength{$size}});
next unless $numSameSize > 1;
if ( $debug ) {
print "size: $size numSameSize: $numSameSize\n";
}
my $filesByMd5Ref = hashByMd5($filesByDataLength{$size});
my %filesByMd5 = %{$filesByMd5Ref};
foreach my $md5 (keys %filesByMd5) {
my @sameMd5List = @{$filesByMd5{$md5}};
my $numSameMd5 = scalar(@sameMd5List);
next unless $numSameMd5 > 1;
my $rsrcMd5;
my $dupe_counter=0;
foreach my $fileInfo (@sameMd5List) {
my $dirname = $fileInfo->{dirname};
my $filename = $fileInfo->{filename};
my $filepath = "$dirname/$filename";
if ( $dupe_counter == 0 ) {
if ( $debug ) {
print "KEEPING $filepath - MD5 $md5\n";
}
$dupe_counter++;
} else {
if ( $debug ) {
print "DELETING $filepath - MD5 $md5\n";
} else {
print "D";
}
unlink("$filepath");
}
}
if ( $debug) {
print "----------\n";
}
$numDupes += ($numSameMd5 - 1);
$numDupeBytes += ($size * ($numSameMd5 - 1));
}
}
print "----------\n";
my $numDupeMegabytes = sprintf("%.1f", $numDupeBytes / (1024 * 1024));
print "Number of duplicate files: $numDupes\n";
print "Estimated Mb Savings: $numDupeMegabytes\n";
}



, Mike