pl 脚本限制 ssh 同时在线

2015-02-10 16:22:19 +08:00
 dingzi
以下代码收集自网络 。 我目的为限制服务器里的各个ssh账号能最多能同时登陆3个。
#!/usr/bin/perl -w
use strict;
#white list
my @ALLOW_USERS = qw{
test
root
};
#the maximum number of ssh login(目前知道这里的数字需要改成3)
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;
}
2320 次点击
所在节点    Linux
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/169873

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX