登陆成功:Accepted password for root from 192.168.44.1 port 50854 ssh2 登陆失败:Failed password for root from 192.168.44.1 port 50854 ssh2 用户不存在:Invalid user test from 192.168.31.50 port 54169
# 获取已经加入黑名单的IP,转换为字典 def getDenyIP(): denyDict = {} with open(hostDeny, 'r') as file: # 使用with语句以确保文件在使用后被正确关闭 for ip in file.readlines(): abnormal = re.search(r'(\d+\.\d+\.\d+\.\d+)', ip) if abnormal: denyDict[abnormal.group(1)] = time.time() return denyDict
# 监控方法 def monitorLog(logFile): # 统计密码错误的次数 tempIP = {} # 获取已经进入黑名单的IP denyDict = getDenyIP() # 读取安全日志 popen = subprocess.Popen('tail -f ' + logFile, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # 开始监控 print("------ SSH防爆破脚本开启 ------") while True: time.sleep(0.1) line = popen.stdout.readline().strip() if line: abnormal_invalid_user = re.search('Invalid user \w+ from (\d+\.\d+\.\d+\.\d+)', str(line)) abnormal_failed_password = re.search('Failed password for \w+ from (\d+\.\d+\.\d+\.\d+)', str(line)) if abnormal_invalid_user and not denyDict.get(abnormal_invalid_user.group(1)): subprocess.getoutput('echo \'sshd:{}\' >> {}'.format(abnormal_invalid_user.group(1), hostDeny)) denyDict[abnormal_invalid_user.group(1)] = time.time() time_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) print('{} --- ip:{} 因为登陆错误用户名 被拉入黑名单'.format(time_str, abnormal_invalid_user.group(1))) elif abnormal_failed_password: ip = abnormal_failed_password.group(1) tempIP[ip] = tempIP.get(ip, 0) + 1 if tempIP[ip] > password_wrong_num and not denyDict.get(ip): subprocess.getoutput('echo \'sshd:{}\' >> {}'.format(ip, hostDeny)) denyDict[ip] = time.time() time_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) print('{} --- ip:{} 因为密码错误次数超过上限 被拉入黑名单'.format(time_str, ip)) # 检查黑名单中的IP地址是否超过解封时间,若超过则解封 end_time = time.time() for ip, start_time in list(denyDict.items()): # 使用list()将字典项转换为列表项以避免在迭代时修改字典大小 if end_time - start_time > unblock_time: subprocess.getoutput('sed -i "/^sshd:{}/d" {}'.format(ip, hostDeny)) denyDict.pop(ip) # 使用 pop() 方法从字典中彻底删除指定键值对 time_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) print('{} --- ip:{} 已从黑名单中解封'.format(time_str, ip))