入侵检测python代码
时间: 2024-04-14 11:24:02 浏览: 21
入侵检测是指通过监控和分析网络流量、系统日志等信息,来检测和识别潜在的入侵行为。下面是一个简单的入侵检测的Python代码示例:
```python
import re
# 定义规则列表,用于匹配恶意IP地址
rules = [
r'192\.168\.\d{1,3}\.\d{1,3}', # 内网IP地址
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', # 公网IP地址
r'\b\d{4}\.\d{4}\.\d{4}\.\d{4}\b' # 身份证号码
]
def detect_intrusion(log):
for rule in rules:
if re.search(rule, log):
return True
return False
# 测试入侵检测函数
log1 = '192.168.1.100 - - [01/Jan/2022:12:00:00] "GET /index.html HTTP/1.1" 200 1234'
log2 = '123.456.789.0 - - [01/Jan/2022:12:00:00] "GET /index.html HTTP/1.1" 200 1234'
log3 = '1234.5678.9012.3456 - - [01/Jan/2022:12:00:00] "GET /index.html HTTP/1.1" 200 1234'
print(detect_intrusion(log1)) # 输出:True
print(detect_intrusion(log2)) # 输出:True
print(detect_intrusion(log3)) # 输出:False
```
上述代码中,我们定义了一个规则列表,用于匹配恶意IP地址和身份证号码。然后,通过`detect_intrusion`函数来检测给定的日志是否包含恶意信息。如果匹配到规则,则返回`True`,表示检测到入侵行为;否则返回`False`,表示未检测到入侵行为。