#!/usr/bin/perl -w # updateHosts.pl Andrew Kesterson andrew@aklabs.net # update the system hosts file with Mike's ad blocking file # patch it up to include the newest entries # this obviously needs to run as root if you're working on /etc/hosts # I'm still learning perl. Don't harsh me too much. use strict; use LWP::Simple; use Socket; use Getopt::Std; use Time::localtime; my $URL = "http://everythingisnt.com/hosts"; my $hostfile = "/etc/hosts"; my $buffer; my %args; my $updating = 0; my $usage = <>$hostfile") or die "Couldn't open $hostfile for writing."; if (defined $args{v} ) { print "Beginning update; due to calls to gethostbyname, the program might appear to hang while waiting to resolve.\n"; } HOSTS: foreach my $host ( @newHosts ) { $host =~ m/(127.0.0.1\s\w.*)/; if ( defined $1 ) { $host = $1; $host =~ s/127.0.0.1\s//; $host =~ s/\s.*//; } else { # this should've returned us a hostname... next; } my @addresses = gethostbyname($host); # just checking to see if it already exists in etc-hosts as 127.0.0.1 @addresses = map { inet_ntoa($_) } @addresses[ 4 ... $#addresses]; foreach my $addr ( @addresses ) { if ( $args{v} ) { print "checking 127.0.0.1 against address for $host : $addr\n"; } if ( $addr eq "127.0.0.1" ) { # skip this one. next HOSTS; } else { if ( $args{v} ) { print "adding $host\n"; } if ( !$updating ) { # add a comment with the date if this is the first entry my $time = localtime; print hostsFile "\n# Updates from ", $time->year+1900 , "-", $time->mon+1, "-", $time->mday, "\n"; $updating = 1; } print hostsFile "127.0.0.1\t", $host, "\n"; } } } close hostsFile;