import re import subprocess import time log_file = '/var/log/suricata/fast.log' ip_set = set() while True: with open(log_file) as file: file.seek(0, 2) # 将文件定位到文件末尾 for line in file: match = re.search(r'\d+\.\d+\.\d+\.\d+', line) if not match: continue ip = match.group() priority = re.search(r'Priority\.+', line).group() if ip in ip_set: continue if 'Priority: 1' in priority or 'Priority: 2' in priority: continue result = subprocess.call(['iptables', '-A', 'INPUT', '-s', ip, '-j', 'DROP']) if result == 0: print(f'封禁IP {ip} 成功!') ip_set.add(ip) else: print(f'封禁IP {ip} 失败!') time.sleep(5)这段代码运行没有任何输出结果,我应该在哪里添加print语句查看输出,或者最后怎么添加异常处理语句
时间: 2023-12-11 07:06:08 浏览: 222
你可以在以下几个位置添加 `print` 语句来查看输出:
1. 在 `while` 循环的开头添加 `print` 语句,以确认程序已经开始运行:
```
import re
import subprocess
import time
log_file = '/var/log/suricata/fast.log'
ip_set = set()
print('程序已经开始运行')
while True:
with open(log_file) as file:
...
```
2. 在成功封禁 IP 的分支中添加 `print` 语句,以确认哪些 IP 被成功封禁:
```
if result == 0:
print(f'封禁IP {ip} 成功!')
ip_set.add(ip)
else:
print(f'封禁IP {ip} 失败!')
```
最后,你可以在代码末尾添加异常处理语句,以处理可能出现的异常情况:
```
import re
import subprocess
import time
log_file = '/var/log/suricata/fast.log'
ip_set = set()
print('程序已经开始运行')
while True:
try:
with open(log_file) as file:
file.seek(0, 2) # 将文件定位到文件末尾
for line in file:
match = re.search(r'\d+\.\d+\.\d+\.\d+', line)
if not match:
continue
ip = match.group()
priority = re.search(r'Priority\.+', line).group()
if ip in ip_set:
continue
if 'Priority: 1' in priority or 'Priority: 2' in priority:
continue
result = subprocess.call(['iptables', '-A', 'INPUT', '-s', ip, '-j', 'DROP'])
if result == 0:
print(f'封禁IP {ip} 成功!')
ip_set.add(ip)
else:
print(f'封禁IP {ip} 失败!')
time.sleep(5)
except Exception as e:
print(f'程序出现异常:{e}')
```
阅读全文