#!/usr/bin/perl # # Perl Process Killer (PPK) # ppk {process name, reqired} {iterations, optional} # use strict; use warnings; my $loop = -1; my @immortal; my $flags; my $process; my $id; my $only_one = 0; my @level = qw/1 2 3 15 9 -9/; sub check_match { die "ACK, GASP: $id failed to match on $_[0]" if( (not $only_one) && ((not defined $_[1]) || (not defined $_[2])) ); die "ACK, GASP: $id failed to match on $_[0]" if($only_one && (not defined $_[1])); } die "ACK, GASP: Need program name to search for!\n" if( (not defined $ARGV[0]) || ($ARGV[0] =~ m/^\s*\d+\s*$/) ); # Other operating systems can be supported, I just do not have access to them # to configure $^O, $flags, $process, and $id properly. # $^O should be matched against the platform you wish to add support for # $flags must be set so "ps $flags" returns (at least) the User ID, Process ID, and Command Name # $process is a regexp that matches against the Command Name # $id is a regexp that matches the User ID and Process ID; putting them into $1 and $2, respectivly # Also, don't forget to anchor your $process and $id matches! if($^O =~ m/linux/i) { $flags = "-ea"; eval { $process = qr/\s+(?:\d+[:])+?\d+\s+.*?$ARGV[0].*?\s*$/; }; if($@) { $@ =~ s/\s+at\s+.*?$0.*$//i; die "ACK, GASP: \"$ARGV[0]\" is an invalid command line argument:\n" . " $@"; } $id = qr/^\s*(\d+)\s+/; $only_one = 1; } elsif($^O =~ m/irix/i) { $flags = "-eaf"; eval { $process = qr/\s+(?:\d+[:])+?\d+\s+.*?$ARGV[0].*?\s*$/; }; if($@) { $@ =~ s/\s+at\s+.*?$0.*$//i; die "ACK, GASP: \"$ARGV[0]\" is an invalid command line argument:\n" . " $@"; } $id = qr/^\s*(\w+)\s+(\d+)\s+/; } else # Provide crippled functionality... { $flags = ""; eval { $process = qr/\d+\s+.*?$ARGV[0].*?\s*$/; }; if($@) { $@ =~ s/\s+at\s+.*?$0.*$//i; die "ACK, GASP: \"$ARGV[0]\" is an invalid command line argument:\n" . " $@"; } $id = qr/^\s*(\d+)\s+/; $only_one = 1; } if( (defined $ARGV[1]) && !($ARGV[1] =~ m/\D/o) && ($ARGV[1] > 0) ) { $loop = int($ARGV[1]); } my $login = (getpwuid($>))[0] || getlogin() || (getpwuid($<))[0]; while($loop != 0) { $loop-- if($loop > 0); foreach (map { $_->[0] } sort { $b->[1] <=> $a->[1] } map { m/$id/; check_match($_, $1, ((not $only_one) ? $2 : "")); [$_, ((not $only_one) ? $2 : $1)] } grep { m/$process/ } `ps $flags`) { m/$id/; check_match($_, $1, ((not $only_one) ? $2 : "")); next if( ((not $only_one) && ($1 ne $login) && ($login ne "root")) || (((not $only_one) ? $2 : $1) == $$) || (scalar grep { ((not $only_one) ? $2 : $1) == $_ } @immortal) ); my $successful = 0; foreach (@level) { if((kill $_, ((not $only_one) ? $2 : $1)) >= 1) { $successful = 1; last; } } if(not $successful) { warn "WARNING: I cannot kill PID " . ((not $only_one) ? $2 : $1) . "!\n"; push @immortal, ((not $only_one) ? $2 : $1); } } sleep(1) if($loop != 0); }