Saturday, July 2, 2016

Perl and Bash Shell Scripts To Download The Latest Driver Packs


#!/bin/bash

/usr/bin/perl /home/mike/code/dpmirror/dpmirror.pl > /dev/null
#cp /home/mike/code/dpmirror/torrents/*.torrent /store/torrent/watch/

#!/usr/bin/perl
# Driver Packs Scrapper v0.1
# Michael Craze 2012
#
# Scrapes the driverpacks.net RSS feed for the latest torrents,
# The RSS feed only give links to the website, so those links are
# scrapped for the links to the torrent files. They are saved in
# the $dest directory with their correct filenames.
# This can be used in conjunction with your torrent client's "watch"
# directory for automatic downloading of latest driver packs.
use strict;
use warnings;
use URI;
use XML::RSS;
use LWP::Simple;
use Web::Scraper;

my $log_file='/home/mike/code/dpmirror/driver_packs.log';
#my $dest='/home/mike/code/dpmirror/torrents';
my $dest='/store/torrent/watch';
my $feed='http://driverpacks.net/driverpacks/latest/feed';

my @driver_packs=();
open my $ILFH, '<', $log_file or die "Can't open $log_file: $!\n";
chomp(@driver_packs=<$ILFH>);
close $ILFH;

my $rss=new XML::RSS;
my $content=get($feed);
die unless $content;
$rss->parse($content);
foreach my $item (@{$rss->{'items'}}){
    next unless defined($item->{'title'}) && defined($item->{'link'});
    my $already_downloaded_flag=0;
    my $title=$item->{'title'};
    my $link=$item->{'link'};
    #
    my $data = scraper {
        process "div.download-link > a", 'urls[]' => '@href';
    };
    my $res = $data->scrape(URI->new("$link"));
    for my $i (0 .. $#{$res->{urls}}){
        print "Checking $link\n";
        my @fields = split /\//, $res->{urls}[$i];
        my $kind=$fields[7];
        my $arch=$fields[6];
        my $ver=$fields[8];
        $ver =~ tr/.//d;
        my $nt="";
        if($fields[5] =~ m/^7$/){ $nt="6"; }
        if($fields[5] =~ m/^xp$/i){ $nt="5"; }
        my $fn=$dest."/DP_".$kind."_wnt".$nt."-".$arch."_".$ver.".torrent";
        next if(-e $fn);
        for my $driver_pack (@driver_packs){
            if($fn =~ m/$driver_pack/){ $already_downloaded_flag=1; }
        }
        next if $already_downloaded_flag;
        push(@driver_packs,$fn);
        my $status=getstore($res->{urls}[$i],$fn);
        if(is_success($status)){
            my $time=localtime();
            print "Updated: $fn [$time]\n";
        }
    }
}

# Write new log file
open my $OLFH, '>', $log_file or die "Can't open $log_file: $!\n";
for my $driver_pack (@driver_packs){
        print $OLFH "$driver_pack\n";
}
close $OLFH;

exit;

__END__

Perl and Bash Shell Scripts To Download All Driver Packs Torrent Files

This is nice to use to mirror the driverpacks. Use with your torrent client's watch directory.


#!/bin/bash
#
# dl_all_dps.sh
#
# Downloads all the torrents for the current lastest releases of driver packs
# for all Windows operating systemss and all their architectures.
# TLDR: Downloads all available driver packs
#
# © Michael Craze -- http://projectcraze.us.to

for x in `lynx -dump http://driverpacks.net/driverpacks/latest | grep "http:\/\/driverpacks\.net\/driverpacks\/windows\/" | awk '{print $2;}'`; do
        #/driverpacks/windows/7/x86/monitors/10.01/download/torrent
        echo "Getting: $x";

        # This should work, but it doesn't - couldn't figure out why so rewrote script in perl
        #lynx -dump "$x" | grep "\/download\/torrent" | awk '{print $2}' | wget -i -
        lynx -force_html -dump "$x" | grep "\/download\/torrent" | awk '{print $2}'
done

#!/usr/bin/perl
#
# Downloads all torrents for all driver packs for all windows operating systems
# and architectures
#
# © Michael Craze -- http://projectcraze.us.to

use strict;
use warnings;
use LWP::Simple;

my $debug=0;
my $domain="http://driverpacks.net";
my $url=$domain."/driverpacks/latest";
my $content=get($url);
die "Couldn't get url: $url" unless defined $content;

if ($debug){
        print "$content\n";
}

my @torrent_links=($content =~ /(\/driverpacks\/windows\/(7|xp)\/(x86|x64)\/[-a-zA-Z]+\/\d+\.\d+)/g);
foreach my $link (@torrent_links){
        if($link =~ /(\/driverpacks\/windows\/(7|xp)\/(x86|x64)\/[-a-zA-Z]+\/\d+\.\d+)/g){
                #print "Getting: $domain"."$link\n";
                my $link_content=get($domain.$link);
                die "Couldn't get url: $url" unless defined $link_content;
                if($debug){
                        print "$link_content\n";
                }
                if($link_content =~ /(\/driverpacks\/windows\/(7|xp)\/(x86|x64)\/[-a-zA-Z]+\/\d+\.\d+\/download\/torrent)/g){
                        my $uri=$domain.$1;
                        print "Downloading: $uri\n";
                        my @dirs=split("/",$1);
                        my $filename="DP_".$dirs[2]."_".$dirs[3]."_".$dirs[4]."_".$dirs[5]."_".$dirs[6].".torrent";
                        print " Filename: $filename\n";
                        my $status=getstore($uri,$filename);
                        die "$status error while getting $uri" unless is_success($status);
                }
        }
}

A Shell Script To Download MVPS Host File And Use It On Our OpenWRT Router


#!/bin/sh

hosts_file="/etc/hosts"
old_hosts_file="old_hosts.txt"
new_hosts_file="new_hosts.txt"

if [ -f $hosts_file ] ; then
    mv $hosts_file ./hosts
    rm -f $HOSTFILE
fi

if [ -f "hosts.txt" ] ; then
    rm -f ./hosts.txt
fi

if [ -f "new_hosts.txt" ] ; then
    rm -f ./new_hosts.txt
fi

cp /etc/hosts ./old_hosts.txt
cat ./hosts | sed -e 's/0\.0\.0\.0.*$/\r/g' -e '/^\s*$/d' > $HOSTFILE
wget http://www.mvps.org/winhelp2002/hosts.txt
cat ./hosts.txt | sed -e 's/^#.*$/\r/g' -e 's/\s*#.*$/\r/g' -e '/^\s*$/d' | sed -e '1,2s/^.*$//g' -e '/^\s*$/d' | sed -e 's/127\.0\.0\.1/0\.0\.0\.0/g' >> $HOSTFILE
#cat $HOSTFILE > /etc/hosts


#wget -O - http://www.mvps.org/winhelp2002/hosts.txt | grep 127.0.0.1 | sed -e '2,$s/127.0.0.1/0.0.0.0/g' -e 's/[[:space:]]*#.*$//' > /etc/hosts
#logger "$0: Hosts-file downloaded"stopservice dnsmasq
#startservice dnsmasq
#logger "$0: DNSMasq restarted"

A Perl Script To Search A Hard Drive For All Images >300x200 Pixels


#!/usr/bin/perl
use strict;
use warnings;
use File::Find::Rule;
use File::Find::Rule::MMagic;
use File::Find::Rule::ImageSize;

if($#ARGV < 0){
    print "usage: ./ppf.pl \n";
    exit 1;
}

my $rule=File::Find::Rule->new;
$rule->file;
$rule->name('*.jpg','*.jpeg','*.png','*.tif','*.tiff'); # check extension
$rule->magic('image/*'); # check the mime type
$rule->image_x('>300'); # pictures will be >=320x240
$rule->image_y('>200');
my @imgz=$rule->in(@ARGV);

foreach my $i (@imgz){
    print "$i\n";
}

A Perl Script To Search A Hard Drive For Filenames Resembling Common Digital Camera Filenames


#!/usr/bin/perl
use strict;
use warnings;
use File::Find;

if($#ARGV != 0){
    print "Usage: ./finddc.pl \n";
    print "E.g.\n";
    print " ./finddc.pl C:\n";
    exit 1;
}

print "Searching $ARGV[0] for camera files...\n";

find({
    preprocess => \&preprocess,
    wanted => \&wanted
}, $ARGV[0]);

sub preprocess {
    my @list;
    foreach (@_){
        if( -d && $_ =~ m/DCIM/){ push @list, $_; }

        # .wav files are ommitted in the search
        if(-f && $_ =~ m/(DSC_|IMG_)\d+(\.jpg|\.tif|\.thm|\.png)/i){
            print "$_\n";
            push @list, $_;
        }

        # file names list came from:
        # http://diddly.com/random/about.html
        # Kodak
        if(-f && $_ =~ m/dcp\d+\.jpg/i){ push @list, $_; }

        # Nikon
        if(-f && $_ =~ m/dsc[n]?\d+\.jpg/i){ push @list, $_; }

        # Sony
        if(-f && $_ =~ m/mvc[-]?\d+\.jpg/i){ push @list, $_; }

        # Olympus
        if(-f && $_ =~ m/P(101|MDD)\d+\.jpg/i){ push @list, $_; }

        # RCA and Samsung
        if(-f && $_ =~ m/IM[A]?G\d+\.jpg/i){ push @list, $_; }

        # Canon
        if(-f && $_ =~ m/1\d+-\d+(_IMG)?\.jpg/i){ push @list, $_; }
        if(-f && $_ =~ m/(I|_)MG_\d+\.jpg/i){ push @list, $_; }

        # Fuji Finepix
        if(-f && $_ =~ m/dscf\d+\.jpg/i){ push @list, $_; }

        # Toshiba PDR
        if(-f && $_ =~ m/pdrm\d+\.jpg/i){ push @list, $_; }

        # HP Photosmart
        if(-f && $_ =~ m/(IM|EX)\d+\.jpg/i){ push @list, $_; }

        # Kodak DC-40,50,120, S is (L)arge (M)edium (S)mall.
        if(-f && $_ =~ m/DC\d+(L|M|S)\.jpg/i){ push @list, $_; }

        # Minolta Dimage
        if(-f && $_ =~ m/pict\d+\.jpg/i){ push @list, $_; }

        # Kodak DC290
        if(-f && $_ =~ m/P\d+\.JPG/i){ push @list, $_; }

        # Casio
        if(-f && $_ =~ m/(YYMDD|MMDD)\d+\.JPG/i){ push @list, $_; }

        # Pentax
        if(-f && $_ =~ m/IMGP\d+\.JPG/i){ push @list, $_; }

        # Panasonic
        if(-f && $_ =~ m/PANA\d+\.JPG/i){ push @list, $_; }

        # HTC Desire Z/Tmobil G2
        if(-f && $_ =~ m/IMG_\d{8}_\d{6}.JPG/i){ push @list, $_; }

        # Facebook
        if(-f && $_ =~ m/\d+_\d+_\d+_n.jpg/i){ push @list, $_; }

    }
    return @list;
}

sub wanted {
    foreach (@_){
        print "$_\n";
    }
    print "done...\n";
}

Crime City Game Mafia Code Auto-Bumper Perl Script

Run the following script like this:


/usr/bin/perl /home/mike/code/ccbumper/ccbumper.pl 2>&1 >> /dev/null &



#!/usr/bin/perl
# http://www.crimecitymafia.com mafia code auto-bumper
# Michael Craze
# 20130304
use strict;
use warnings;
use WWW::Mechanize;

# To get the following value, you have to go through the source code of the site
# and find the hidden form input field named bk, the value will need to be
# copied and pasted below.
my $bk = "f22f8cea8023e53d82c1ea51ee38b746";

# Read mafia codes from codes.txt and store in @codes array
my $code_file = "codes.txt";
open(FH, "< $code_file") or die "Can't open $code_file for read: $!";
my @codes=();
while(){
    if($_ =~ m/\d\d\d-\d\d\d-\d\d\d/){
        push(@codes, $_);
    }
}
close FH or die "Cannot close $code_file: $!";

my $url = "http://www.crimecitymafia.com/";
my $m = WWW::Mechanize->new( agent => 'Apple-iPhone4C1/901.406'); # iphone 4s
while(1){
    for(my $i=0; $i < scalar(@codes); $i++){
        #my $wait_time = int(rand(60)); # random int [0,60]
        $m->get($url);
        $m->form_number(2);
        $m->field('package', '1');
        $m->field('bk', $bk);
        $m->field('code', $codes[$i]);
        $m->submit();
        #my $response = $m->submit();
        #print $response->content();
    }
    sleep(3600);
}

A Forkbomb Written In C


/* forkbomb.c
   Michael Craze
   http://projectcraze.ath.cx
*/

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>

void usage(char *s);

int main(int argc, char **argv){
    int i, fv, iter;
    if(argc != 2){
        usage(argv[0]);
    }
    iter=atoi(argv[1]);
    for(i=0;i<iter;i++){
        if((fv=fork())==-1){
            perror(argv[0]);
        }
        else if(fv==0){
            sleep(1000);
        }
        else{
            printf("Process: %8d -- i/iter = %d/%d\n",getpid(),i,iter);
            fflush(stdout);
        }
    }
    return 0;
}

void usage(char *s){
    fprintf(stderr,"Usage: %s \n",s);
    fprintf(stderr," *Note: fork calls scale logrithmically\n");
    exit(1);
}

Adding To The Simple Port Scanner Written in C


/*
    TCP port scanner
    Written and Maintained by Michael Craze

TODO:
    make it use threads..
    make it check UDP
    make it scan ip address ranges for public use

    ip address ranges for private use:
    Class   Networks
    A   10.0.0.0 through 10.255.255.255
    B   172.16.0.0 through 172.31.0.0
    C   192.168.0.0 through 192.168.255.0
*/

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

typedef struct{
    char *ip;
    int sport;
    int eport;
} Host;

void usage(char *a){
    fprintf(stderr,"Invalid invocation of %s\n",a);
    printf("Usage: %s   \n",a);
    exit(1);
}

/* Main programs starts*/
int main(int argc, char **argv){
    int sd;
    int port;
    int rval;
    int checkip;
    int pcount = 0;

    /* going to use these ints to iterate
       through public IP classes to find all
       open servers to automate attacks.
    */
    /*
       int A,B,C,D;
    */

    /*
        char *message="shell";
    */
    /*
        char response[1024];
    */

    Host *h;
    struct hostent *hostaddr;
    struct sockaddr_in servaddr;

    if (argc < 4 ){
        usage(argv[0]);
    }

    h = (Host *)malloc(sizeof(Host));
    if(h == NULL){
        fprintf(stderr,"couldn't allocate memory for %s\n",argv[1]);
        exit(1);
    }
    if(sscanf(argv[1],"%d",&checkip) != 1){
        fprintf(stderr,"%s was not a valid ip address\n",argv[1]);
        usage(argv[0]);
    }
    if(sscanf(argv[2],"%d",&h->sport) != 1){
        fprintf(stderr,"%s was not a valid integer\n",argv[2]);
        usage(argv[0]);
    }
    if(sscanf(argv[3],"%d",&h->eport) != 1){
        fprintf(stderr,"%s was not a valid integer\n",argv[3]);
        usage(argv[0]);
    }

    h->ip = strdup(argv[1]);
    printf("Scanning host: %s on ports %d thru %d\n", h->ip,h->sport,h->eport);


    /* Start scanning ports */
    for (port = h->sport; port <= h->eport; port++){
        /* creating the tcp socket */
        sd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
        if (sd == -1){
            perror("Socket()\n");
            return (errno);
        }
        memset( &servaddr, 0, sizeof(servaddr));
        servaddr.sin_family = AF_INET;
        servaddr.sin_port = htons(port);
        hostaddr = gethostbyname(h->ip);

        memcpy(&servaddr.sin_addr, hostaddr->h_addr, hostaddr->h_length);

        /* below connects to the specified ip in hostaddr */
        rval = connect(sd, (struct sockaddr *) &servaddr, sizeof(servaddr));

        if(rval != -1){
            printf("  %-7d %-10s\n",port,"is open");
            pcount++;
        }
        close(sd);
    }
    if(pcount == 0){
        printf("No ports in range %d-%d are open on host %s\n",h->sport,h->eport,h->ip);
    }
    else{
        printf("%d ports in range %d-%d are open on host %s\n",pcount,h->sport,h->eport,h->ip);
    }

    free(h);
    return 0;
}

A Simple Port Scanner Written In C


#include<stdio.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<stdlib.h>
#include<netdb.h>
int main(int argc,char **argv)
{
        int i,err,net;
        struct hostent *host;
        struct sockaddr_in sa;
        if(argc!=2){
                printf("Error...Usage :%s ip-address",argv[0]);
                exit(0);
        }
        for(i=1;i<20000;i++){
                sa.sin_family=AF_INET;
                sa.sin_port=htons(i);
                sa.sin_addr.s_addr=inet_addr(argv[1]);
                net=socket(AF_INET,SOCK_STREAM,0);
            err=connect(net,(struct sockaddr_in *)&sa,sizeof(sa));
        if(err>=0){
                        printf("\n%d is open",i);
                }
                close(net);
        }
        printf("\n");
}

Hack In The Box Magazine Perl Script To Download All Issues As PDF

I wrote this a long time ago to scrape the Hack in the Box site and download all their magazines in PDF format:


#!/usr/bin/perl
# Downloads Hack In The Box Magazines
use strict;
use warnings;
use LWP::Simple;

for (my $i=1;$i<1000;$i++){
    my $url=sprintf("http://magazine.hitb.org/issues/HITB-Ezine-Issue-%03d.pdf",$i);
    my $pdf=sprintf("HITB-Ezine-Issue-%03d.pdf",$i);
    next if (-e $pdf);
    my $status=getstore($url,$pdf);
    if(is_error($status)){
        print "[$status] Couldn't download: $url\n";
        last;
    }
    else{
        print "[$status] Downloaded: $url\n";
    }
}

Using Python and Bash Scripts and sSMTP to Notify You by E-mail When a New Issue of 2600: The Hacker Quarterly Is Released

I wrote this python script to get notified when a new issue of 2600: The Hacker Quarterly is released:


#!/usr/bin/python
import re
import feedparser
url = 'http://www.2600.com/rss.xml'
f = "log.txt"
d = feedparser.parse(url)
fh = open(f, 'r+')
line = fh.readline()
if line != d['entries'][0]['link']:
        if re.match(r'(WINTER|SPRING|SUMMER|AUTUMN).*', d['entries'][0]['title']):
                print d['entries'][0]['title'] + " " + d['entries'][0]['link'] + "\r\n"
fh.seek(0)
fh.write(d['entries'][0]['link'] + "\r\n")
fh.truncate()
fh.close()


And here is the Bash Shell script to take the output from stdout and use it as the subject for an e-mail:


#!/bin/bash
#
# Executes the script given as argument #2,
# then if there is anything printed to stdout,
# it will email the text as the body of the email
#
# © Michael Craze -- http://projectcraze.us.to

if [ "$#" -ne 2 ] ; then
        echo "Usage: $0  <2600_script>"
        exit
fi

EMAIL="your_email@domain.com"
SUBJECT=$1
CLSCRIPT=$2
PY=`which python`
MAIL=`which mail`
BODY=`$PY $CLSCRIPT`

# send email if something was posted today
if [ -n "$BODY" ] ; then
        echo $BODY | $MAIL -s $SUBJECT $EMAIL
fi


Here is the crontab (crontab -e) entry I use to run it once daily:


30 8 * * * /bin/bash /home/mike/code/2600_notifier/2600-mail.sh New_2600 /home/mike/code/2600_notifier/2600_notifier.py


This will only work if you have your MTA setup correctly. I use a package called ssmtp (sudo apt-get install ssmtp), and set it up to use my gmail account to send mail, here is my ssmtp.conf:


# Config file for sSMTP sendmail
#
# The person who gets all mail for userids < 1000
# Make this empty to disable rewriting.
#root=postmaster
root=your_email@gmail.com

# The place where the mail goes. The actual machine name is required no
# MX records are consulted. Commonly mailhosts are named mail.domain.com
#mailhub=mail
mailhub=smtp.gmail.com:587

AuthUser=your_email@gmail.com
AuthPass=your_password
UseTLS=YES
UseSTARTTLS=YES

# Where will the mail seem to come from?
#rewriteDomain=
rewriteDomain=gmail.com

# The full hostname
#hostname=MyMediaServer.home
hostname=your_email@gmail.com

# Are users allowed to set their own From: address?
# YES - Allow the user to specify their own From: address
# NO - Use the system generated From: address
FromLineOverride=YES