一个简单的禁止ssh暴力登录Python脚本

469 阅读1分钟

查看/var/log/secure 文件可以看到很多认证失败的Failure的ip登录信息。所以根据secure日志文件查看失败的ip如果超过3次,那么就把此ip写入/etc/hosts.deny文件,禁止此ip登录。

收集 /var/log/secure 里面的信息,若是某个IP 链接次数超过设定的次数 ,则把此ip记录到/etc/hosts.deny里面禁止登录。

#!/usr/bin/env python

# -*- coding: utf-8 -*-

with open('/etc/hosts.deny') as f:    #获取已经禁止的IP

    deny = f.read().split('\n')

with open('/var/log/secure') as f:    #获取所有的记录

    log = f.read().split('\n')

ipset = [ ]    #创建一个空的列表

for l in log:

    if 'Failed password' in l:

        ip = l.split(' from ')[1].split(' port ')[0]    #从记录中取得IP

        ipset.append( "sshd:" + ip )    #以sshd:ip 这种形式保存在列表中

a=set(ipset)     #创建一个IP的集合

for j in a:

    if ipset.count(j) > 3:   #判断输错密码的次数

        with open('/etc/hosts.deny', 'a') as f:    #打开文件

            if j not  in deny:      #去重判断,如果不在已经存在的禁止IP中就写入

                f.write(j + '\n')