perl脚本实现限制ssh最大登录次数(支持白名单)(perl脚本调试方法)学会了吗

随心笔谈11个月前发布 admin
89 0


#!/usr/bin/perl -w
use strict;
#white list
my @ALLOW_USERS=qw{
test
root
lulu1
};
#the maximum number of ssh login
my $LOGIN_TIMES=1;
sub main
{
my @lines=`ps -eo user,pid,etime,cmd | grep sshd`;
my $users;
for my $line (@lines) {
if(my ($user, $pid, $etime, $cmd)=$line=~ /^([^\s]+)\s+(\d+)\s+([^\s]+)\s+(sshd:.+)$/) {
next if grep {$user eq $_} @ALLOW_USERS;
my $proc={‘pid’, $pid, ‘etime’, $etime, ‘cmd’, $cmd};
push @{$users->{$user}}, $proc;
}
}
for my $key(keys(%$users)) {
my @sshs=sort {
my ($lb, $la)=(length($b->{‘etime’}), length($a->{‘etime’}));
if($lb==$la) {
$b->{‘etime’} cmp $a->{‘etime’};
} else {
$lb <=> $la;
}
} @{$users->{$key}};
$LOGIN_TIMES=1 if $LOGIN_TIMES < 1;
for (1 .. $LOGIN_TIMES) { pop @sshs; };
for my $ssh (@sshs) {
kill 9, $ssh->{‘pid’};
}
}
}
while(1) {
main;
sleep 3;
}

© 版权声明

相关文章