Created
January 27, 2012 22:40
-
-
Save norrs/1691342 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
## dotkom kill, dkill.pl | |
## Roy Sindre Norangshol, <norangsh> | |
use Getopt::Std; | |
use strict; | |
use vars qw/ %opt /; | |
my $MAX_HOURS = 4; | |
sub init() { | |
getopts("hdDvn:e:", \%opt); | |
$MAX_HOURS = int($opt{n}) if ($opt{n} and int($opt{n})>0) ; | |
$opt{v} = 1 if $opt{d}; # enables verbose if dry-run. | |
usage() if ($opt{h} or (not $opt{d} and not $opt{v}) or not $opt{e}); | |
KillOldProcesses(); | |
} | |
sub KillOldProcesses() { | |
print "DRY-RUN , not killing anything ..\n" if $opt{d}; | |
print "max-hours: $MAX_HOURS\n" if $opt{D}; | |
print "expression: $opt{e}\n" if $opt{D}; | |
my $any_hits = undef; | |
open(PS, "ps -eo '%U\t%p\t%t\t%a' --sort user |") || die "Failed: $!\n"; | |
while (<PS>) { | |
my ($user,$pid,$elapsed,$args) = split(/\t/); | |
if ($args=~/$opt{e}/ && $elapsed =~/(\d{0,9})-(\d{1,2}):\d{1,2}:\d{1,2}/) { | |
if ($2) { | |
my($hours) = int($2); | |
if ($1) { | |
$hours = (int($1)*24)+$hours; ## add days*24hours to elapsed hours | |
} | |
if ($hours>=$MAX_HOURS) { | |
if (not $any_hits) { | |
print "Killing processes older then $MAX_HOURS hours by expression: $opt{e}\n\n" if $opt{v}; | |
$any_hits = 1; | |
} | |
print "Killing(SIGTERM) $user, pid $pid running $hours hours\t: $args" if $opt{v}; | |
system("kill $pid") if not $opt{d}; | |
} | |
} | |
} | |
} | |
close(PS); | |
} | |
sub usage() { | |
print STDERR << "EOF"; | |
This program lets you kill processes if they are older then "\$MAX_HOURS" hours | |
usage: $0 [-hdve] EXPRESSION to match against commandname with arguments in ps | |
-h : this (help) message | |
-v : verbose output | |
-d : dry run, will enable verbose and not execute the kills | |
-D : debug (more verbose output) | |
-n : kill processes older then #n hours , defaults to 4 hours. | |
-e : EXPRESSION | |
example: $0 -ve python manage.py | |
EOF | |
exit; | |
} | |
init(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment