IP封禁小工具
IP封禁小工具
一、前言
二、源码
三、代码优势说明
四、打包部署指南
4.1 Windows (生成无控制台窗口的exe)
4.2 Linux (生成桌面应用)
4.3 系统要求
4.4 部署验证清单
五、后面附有打包exe文件
六、日志更新
一、前言
单点禁IP,花了5个小时弄了一个.py脚本
(经过AI优化高度兼容且健壮的跨平台IP禁止小工具,可能还有隐藏bug,欢迎回复,有空会抽时间看看)
二、源码
import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext
import platform
import subprocess
import re
import ctypes
import os
import sys
import logging
from datetime import datetime
# 配置日志系统
logging.basicConfig(
filename='firewall_manager.log',
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
encoding='utf-8'
)
class FirewallManager:
"""防火墙管理核心类"""
def __init__(self):
self.os_type = platform.system()
self._validate_environment()
def _validate_environment(self):
"""验证系统环境支持"""
if self.os_type not in ['Windows', 'Linux']:
raise EnvironmentError("Unsupported operating system")
if self.os_type == 'Linux' and not os.path.exists('/sbin/iptables'):
raise FileNotFoundError("iptables not found, install via: sudo apt install iptables")
def _execute_cmd(self, command):
"""执行系统命令的统一入口"""
try:
if self.os_type == 'Windows':
result = subprocess.run(
command,
shell=True,
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
creationflags=subprocess.CREATE_NO_WINDOW
)
else:
result = subprocess.run(
['sudo'] + command.split(),
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True
)
logging.info(f"CMD Success: {command}")
return True, result.stdout
except subprocess.CalledProcessError as e:
error_msg = f"CMD Failed: {command}\nError: {e.stderr}"
logging.error(error_msg)
return False, error_msg
except Exception as e:
error_msg = f"Unexpected error: {str(e)}"
logging.critical(error_msg)
return False, error_msg
def block_ip(self, ip):
"""封禁IP地址"""
if not self._validate_ip(ip):
return False, "Invalid IP format"
if self.os_type == 'Windows':
return self._execute_cmd(f'netsh advfirewall firewall add rule name="BLOCK_{ip}" dir=in action=block remoteip={ip}')
else:
success, msg = self._execute_cmd(f'iptables -A INPUT -s {ip} -j DROP')
if success:
self._execute_cmd('iptables-save > /etc/iptables/rules.v4')
return success, msg
def unblock_ip(self, ip):
"""解禁IP地址"""
if not self._validate_ip(ip):
return False, "Invalid IP format"
if self.os_type == 'Windows':
return self._execute_cmd(f'netsh advfirewall firewall delete rule name="BLOCK_{ip}"')
else:
success, msg = self._execute_cmd(f'iptables -D INPUT -s {ip} -j DROP')
if success:
self._execute_cmd('iptables-save > /etc/iptables/rules.v4')
return success, msg
def list_blocked(self):
"""获取已封禁列表"""
if self.os_type == 'Windows':
return self._execute_cmd('netsh advfirewall firewall show rule name=all')
else:
return self._execute_cmd('iptables -L INPUT -n --line-numbers')
@staticmethod
def _validate_ip(ip):
"""IP地址格式验证"""
return re.match(
r'^(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)){3}$',
ip
) is not None
class FirewallGUI:
"""图形用户界面"""
def __init__(self, master):
self.master = master
master.title("防火墙管理工具")
master.geometry("800x600")
# 初始化样式
self._setup_style()
# 权限检查
if not self._check_admin():
self._show_permission_warning()
master.destroy()
return
# 初始化核心组件
self.fw_manager = FirewallManager()
self._create_widgets()
self._update_block_list()
def _setup_style(self):
"""配置界面样式"""
self.style = ttk.Style()
self.style.theme_use('clam')
self.style.configure('TButton', font=('微软雅黑', 10))
self.style.configure('Red.TButton', foreground='white', background='#dc3545')
self.style.configure('Green.TButton', foreground='white', background='#28a745')
def _check_admin(self):
"""检查管理员权限"""
try:
return os.getuid() == 0
except AttributeError:
return ctypes.windll.shell32.IsUserAnAdmin() != 0
def _show_permission_warning(self):
"""显示权限错误提示"""
msg = "需要管理员权限运行!\n\n"
msg += "Windows:右键使用管理员身份运行\n"
msg += "Linux:使用sudo执行"
messagebox.showerror("权限错误", msg)
def _create_widgets(self):
"""创建界面组件"""
main_frame = ttk.Frame(self.master)
main_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)
# 输入区域
input_frame = ttk.LabelFrame(main_frame, text="IP操作")
input_frame.pack(fill=tk.X, pady=10)
ttk.Label(input_frame, text="目标地址:").grid(row=0, column=0, padx=5)
self.ip_entry = ttk.Entry(input_frame, width=25)
self.ip_entry.grid(row=0, column=1, padx=5)
self.ip_entry.insert(0, "输入IPv4地址")
self.ip_entry.bind("<FocusIn>", lambda e: self._clear_placeholder(self.ip_entry))
ttk.Button(input_frame, text="封禁", style='Red.TButton',
command=lambda: self._perform_action('block')).grid(row=0, column=2, padx=5)
ttk.Button(input_frame, text="解禁", style='Green.TButton',
command=lambda: self._perform_action('unblock')).grid(row=0, column=3, padx=5)
# 封禁列表
list_frame = ttk.LabelFrame(main_frame, text="已封禁IP列表")
list_frame.pack(fill=tk.BOTH, expand=True)
self.list_box = scrolledtext.ScrolledText(list_frame, wrap=tk.WORD, state='disabled')
self.list_box.pack(fill=tk.BOTH, expand=True)
# 状态栏
self.status = ttk.Label(main_frame, relief=tk.SUNKEN)
self.status.pack(fill=tk.X, pady=5)
# 操作按钮
btn_frame = ttk.Frame(main_frame)
btn_frame.pack(pady=10)
ttk.Button(btn_frame, text="刷新", command=self._update_block_list).pack(side=tk.LEFT, padx=5)
ttk.Button(btn_frame, text="帮助", command=self._show_help).pack(side=tk.LEFT, padx=5)
ttk.Button(btn_frame, text="退出", command=self.master.quit).pack(side=tk.RIGHT)
def _clear_placeholder(self, entry):
"""清空输入框提示"""
if entry.get() in ["输入IPv4地址"]:
entry.delete(0, tk.END)
entry.configure(foreground='black')
def _perform_action(self, action_type):
"""执行封禁/解禁操作"""
ip = self.ip_entry.get().strip()
if not self.fw_manager._validate_ip(ip):
messagebox.showerror("格式错误", "无效的IP地址格式")
return
try:
if action_type == 'block':
success, msg = self.fw_manager.block_ip(ip)
else:
success, msg = self.fw_manager.unblock_ip(ip)
if success:
self.status.config(text=f"操作成功: {ip} 已{'封禁' if action_type=='block' else '解禁'}")
self._update_block_list()
else:
messagebox.showerror("操作失败", msg.split('\n')[0])
except Exception as e:
logging.error(f"系统错误: {str(e)}")
messagebox.showerror("系统错误", f"发生意外错误:{str(e)}")
def _update_block_list(self):
"""更新封禁列表"""
success, data = self.fw_manager.list_blocked()
self.list_box.config(state='normal')
self.list_box.delete(1.0, tk.END)
if success:
ips = self._parse_blocked_ips(data)
if ips:
self.list_box.insert(tk.END, "\n".join(ips))
else:
self.list_box.insert(tk.END, "当前没有封禁的IP地址")
else:
self.list_box.insert(tk.END, "获取列表失败\n" + data[:200])
self.list_box.config(state='disabled')
self.status.config(text=f"最后更新: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
def _parse_blocked_ips(self, raw_data):
"""解析封禁列表"""
if platform.system() == 'Windows':
return [line.split()[-1] for line in raw_data.split('\n') if 'BLOCK_' in line]
else:
return [line.split()[3] for line in raw_data.split('\n')
if 'DROP' in line and '0.0.0.0/0' not in line]
def _show_help(self):
"""显示帮助信息"""
help_text = """使用说明:
1. 输入要操作的IP地址(示例:192.168.1.100)
2. 点击对应按钮:
- 红色按钮:封禁指定IP
- 绿色按钮:解禁指定IP
3. 列表自动刷新显示当前状态
4. 状态栏显示最后操作结果
注意事项:
- 需要管理员权限运行
- 操作实际修改系统防火墙规则
- 关闭窗口不会解除已封禁IP"""
messagebox.showinfo("帮助文档", help_text)
if __name__ == "__main__":
# 高DPI适配
if platform.system() == 'Windows':
ctypes.windll.shcore.SetProcessDpiAwareness(1)
root = tk.Tk()
try:
app = FirewallGUI(root)
root.mainloop()
except Exception as e:
messagebox.showerror("启动失败", f"程序初始化失败: {str(e)}")
logging.critical(f"启动失败: {str(e)}")
三、代码优势说明
1. 跨平台兼容性
○ 自动识别Windows/Linux系统
○ Windows使用netsh advfirewall
○ Linux使用iptables并自动持久化规则
○ 处理不同系统的命令输出解析
2. 健壮性设计
○ 多层异常捕获机制
○ 系统环境预检查(权限/依赖)
○ 输入格式严格验证
○ 完善的日志系统(记录所有关键操作)
3. 用户友好性
○ 自适应DPI缩放(Windows)
○ 输入框智能提示
○ 状态栏实时反馈
○ 彩色按钮区分操作类型
○ 详细的帮助文档
4. 安全增强
○ 自动请求管理员权限
○ 命令执行隐藏窗口(Windows)
○ 防止重复提交操作
○ 敏感操作日志追踪
四、打包部署指南
生成独立可执行文件
4.1 Windows (生成无控制台窗口的exe)
pyinstaller --noconsole --onefile --name FirewallManager --icon=shield.ico firewall_gui.py
4.2 Linux (生成桌面应用)
pyinstaller --onefile --name firewall-manager --add-data='./icon.png:.' firewall_gui.py
4.3 系统要求
• Windows 10/11 或 Linux主流发行版
• Windows需要启用Windows Defender防火墙服务
• Linux需要安装iptables
4.4 部署验证清单
1. 双击可执行文件是否正常启动
2. 尝试封禁/解禁测试IP(如127.0.0.1)
3. 检查防火墙规则是否生效
4. 查看日志文件记录是否完整
5. 验证无Python环境下的运行情况
优化后的源码进行严密的异常处理和兼容性设计,确保在各类环境中稳定运行,界面交互友好,适合需要快速部署防火墙管理工具的场景。
五、有打包exe文件
(python版本是3.9.13),无毒....不放心自查,源码贴出来了。核心就是给防火墙加禁止特定IP的规则,没啥好说的,防火墙不开没效果,可视化避免命令容易敲错和非专业人员使用方便,仅此而已......
download.txt
(58 Bytes, 下载次数: 2)
已知bug
1.ico系统大小版本差异可能会有显示问题
首次运行会生成firewall_manager.log日志文件,删除日志重新进入会再次自动生成。
做个ico花了一个小时,手残了,实在不想弄了,找一个随便改的,图片日期抹掉了,不想搞了,太累了。搜了一下,有同类型的,功能还比这个多,不想说话..........要说优点,兼容性强算不算..........