虚位以待(AD)
虚位以待(AD)
首页 > 脚本专栏 > perl > perl脚本实现限制ssh最大登录次数(支持白名单)

perl脚本实现限制ssh最大登录次数(支持白名单)
类别:perl   作者:码皇   来源:互联网   点击:

这篇文章主要介绍了perl脚本实现限制ssh最大登录次数,脚本支持支持白名单设置,例如root可以不限制登录次数,需要的朋友可以参考下

ssh limit perl脚本主要作用:
1.限制一个ssh用户的最大登录数为n,n可自定义。
2.支持白名单,如root、test登录不受限制。

如果一个ssh用户的最大登录数超过指定数字,则后登录的会把先前登录的踢掉,以此达到控制登录数的目的。

该脚本需要主机支持perl,如果没有,可yum安装。

脚本源码:

    #!/usr/bin/perl -wuse strict;
    #white listmy @ALLOW_USERS = qw{
    test root lulu1}
    ;
    #the maximum number of ssh loginmy $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;
    }


【使用方法】

另存脚本存到root目录,命名为limit.pl,然后执行:

    echo "/root/limit.pl &" >> /etc/rc.d/rc.local (加入开机启动)/root/limit.pl & (运行脚本)

相关热词搜索: perl脚本 限制ssh最大登录次数