Python 解析waf日志以获取主机ip以防止dos攻击

Python 解析waf日志以获取主机ip以防止dos攻击,python,amazon-web-services,aws-lambda,amazon-waf,Python,Amazon Web Services,Aws Lambda,Amazon Waf,我试图创建一个报告,其中如果一个ip请求在一分钟内攻击服务器超过1000次,则为dos攻击。Aws waf正在s3中记录日志,我们将使用lambda检查某些ip是否超过阈值 导入URL库 进口boto3 导入gzip s3=boto3.client('s3') def lambda_处理程序(事件、上下文): #主要配置变量 请求限制=100 # Parsing the required information out of the event structure bucket_name = e

我试图创建一个报告,其中如果一个ip请求在一分钟内攻击服务器超过1000次,则为dos攻击。Aws waf正在s3中记录日志,我们将使用lambda检查某些ip是否超过阈值

导入URL库 进口boto3 导入gzip

s3=boto3.client('s3')

def lambda_处理程序(事件、上下文): #主要配置变量 请求限制=100

# Parsing the required information out of the event structure
bucket_name = event['Records'][0]['s3']['bucket']['name']
file_name = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'])
response = s3.get_object(Bucket=bucket_name, Key=file_name)
target_bucket='blocketrequest'
FILE='Filtered' + file_name

text = response["Body"].read().decode()
e  = text.split("\n")




# Parsing IPs out of the access log file
suspicious_ips = {}

for each in e:
    try:
        loaded_data = json.loads(each)
        ip = loaded_data['httpRequest']['clientIp']
        if ip in suspicious_ips.keys():
            suspicious_ips[ip] += 1
        else:
            suspicious_ips[ip] = 1
    except Exception as err:
        print(f"Problem with line:{str(err)}")
        break

# Filtering IPs that exceeded the limit and preparing inserts to WAF
updates_list = []
for ip in suspicious_ips.keys():
    if suspicious_ips[ip] < requests_limit:
        continue

updates_list.append({
    'Action': 'INSERT',
    'IPSetDescriptor': {
        'Type': 'IPV4',
        'Value': "%s/32"%ip
    }
})

# Exit if there are no malicious IPs
if updates_list == []:
    return

s3.put_object(Body=updates_list,Bucket=target_bucket,Key=FILE)
print('transferred')
#从事件结构中解析所需信息
bucket_name=event['Records'][0]['s3']['bucket']['name']
文件\u name=urllib.parse.unquote\u plus(事件['Records'][0]['s3']['object']['key'])
response=s3.get\u对象(Bucket=Bucket\u名称,Key=file\u名称)
目标_bucket='blocketrequest'
FILE='Filtered'+文件名
text=response[“Body”].read().decode()
e=文本。拆分(“\n”)
#从访问日志文件中解析IP
可疑的_ips={}
对于e中的每一项:
尝试:
loaded_data=json.loads(每个)
ip=加载的_数据['httpRequest']['clientIp']
如果ip位于可疑的\u ips.keys():
可疑ip[ip]+=1
其他:
可疑ip[ip]=1
除异常作为错误外:
打印(f“行有问题:{str(err)}”)
打破
#筛选超出限制的IP并准备插入WAF
更新\u列表=[]
对于可疑的ip_ips.keys()中的ip:
如果可疑的ip[ip]<请求限制:
持续
更新\u list.append({
“操作”:“插入”,
“IPSetDescriptor”:{
“类型”:“IPV4”,
“值”:%s/32”%ip
}
})
#如果没有恶意IP,请退出
如果更新\u列表==[]:
回来
s3.put_对象(Body=更新_列表,Bucket=目标_Bucket,Key=文件)
打印('已传输')

在这段代码中,我在第44行遇到了意图错误。有人能帮我吗?

你可以用很多方法进行语法检查。我喜欢在python插件中使用VisualStudio代码

您还可以要求python编译代码,而无需运行python来检查文件

Python3显示您的文件没有错误

$ python3 -m py_compile 61327893.py
$
我假设您没有使用2.7,但这里是相同的命令

$ python2.7 -m py_compile 61327893.py
  File "61327893.py", line 35
    print(f"TotalRecords:{len(e)}")
                                 ^
SyntaxError: invalid syntax
另一个非微软的好选择是这个在线pep8检查器。


你能把你看到的stacktrace贴出来吗?错误可能在导入的代码中。

这可能会适得其反,但您查看过Amazon Athena吗?它允许您在SQL中轻松查询日志。我想Python也有Athena SDK。

嗨,谢谢你的帮助,我可以解决这个错误,但现在我有另一个错误,“errorMessage”:“赋值前引用的局部变量'ip'”,“errorType”:“UnboundLocalError”,“stackTrace”:[[“/var/task/lambda_function.py”,50,“lambda_handler”,“'Value':\%s/32\%ip”]]