Python武器库开发-Linux系统ssh暴力破解密码自动断阻器(二十)

Linux系统ssh暴力破解密码自动断阻器

关于Linux系统遭遇ssh暴力破解时,我们需要对相关进行暴力破解的非法IP进行封禁,提供以下的脚本,我们只需要在遭遇ssh暴力破解行为的Linux系统上运行该脚本,该脚本便会自动封禁进行ssh远程登陆暴力破解行为的IP,脚本的详细内容如下:

python 复制代码
#!/usr/bin/env python3

import re
import subprocess
import time

#安全日志
logFile = '/var/log/secure'
#黑名单
hostDeny = '/etc/hosts.deny'

#封禁阈值
password_wrong_num = 5


#获取已经加入黑名单的IP,转换为字典
def getDenies():
    deniedDict = {}
    list = open(hostDeny).readlines()
    for ip in list:
        group = re.search(r'(\d+\.\d+\.\d+\.\d+)', ip)
        if group:
            deniedDict[group[1]] = '1'
    return deniedDict


#监控方法
def monitorLog(Logfile):
    #统计密码错误的次数
    tempIp = {}
    #已经拉黑的IP
    deniedDict = getDenies()
    #读取安全日志
    popen = subprocess.Popen('tail -f' + logFile,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
    #开始监控
    while True:
        time.sleep(0.1)
        line = popen.stdout.readline().strip()
        if line:
            group = re.search('Invalid user \w+ from (\d+\.\d+\.d+\.\d+)',str(line))
            #提示不存在用户直接封IP
            if group and not deniedDict.get(group[1]):
                subprocess.getoutput('echo \' sshd:{} >> {}'.format(group[1],hostDeny))
                deniedDict[group[1]] = '1'
                time_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
                print('{} --- add ip:{} to hosts.deny for invalid usr'.format(time_str, group[1]))
                continue

            #用户存在,但密码错误
            group = re.search('Failed password for \w+ from (\d+\.\d+\.d+\.\d+)',str(line))
            if group:
                ip = group[1]
                #统计IP登陆密码错误的次数
                if not tempIp.get(ip):
                    tempIp[1] = 1
                else:
                    tempIp[ip] = tempIp[ip] + 1

                #如果错误次数大于阈值的时候,直接封禁该IP
                if tempIp[ip] > password_wrong_num and not deniedDict.get(ip):
                    del tempIp[ip]
                    subprocess.getoutput('echo \' sshd:{} >> {}'.format(ip,hostDeny))
                    deniedDict[ip] = '1'
                    time_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
                    print('{} --- add ip:{} to hosts.deny for invalid password'.format(time_str, group[1]))


if __name__ == '__main__':
    monitorLog(logFile)
相关推荐
乾巫宇宙国监察特使几秒前
Python的设计模式
python·测试
Hockor9 分钟前
写给前端的 Python 教程四(列表/元组)
前端·后端·python
dessler12 分钟前
代理服务器-LVS的DR模式
linux·运维·云计算
这里有鱼汤18 分钟前
熟练掌握MACD这8种形态,让你少走三年弯路(附Python量化代码)| 建议收藏
后端·python
lubiii_23 分钟前
SQL手工测试(MySQL数据库)
数据库·mysql·web安全·网络安全
404.Not Found26 分钟前
Day46 Python打卡训练营
开发语言·python
love530love28 分钟前
【PyCharm必会基础】正确移除解释器及虚拟环境(以 Poetry 为例 )
开发语言·ide·windows·笔记·python·pycharm
运维开发王义杰36 分钟前
Python: 告别 ModuleNotFoundError, 解决 pipx 环境下 sshuttle 缺少 pydivert 依赖的终极指南
开发语言·python
DanCheng-studio1 小时前
毕设 基于机器视觉的驾驶疲劳检测系统(源码+论文)
python·毕业设计·毕设
carpell1 小时前
【语义分割专栏】3:Segnet实战篇(附上完整可运行的代码pytorch)
人工智能·python·深度学习·计算机视觉·语义分割