如何使用Python读取和添加Windows防火墙中的规则

问题描述 投票:0回答:2

我正在创建一个需要持续监控防火墙的服务,以防止毫无戒心的用户移除服务的大门。我的目的是使用 python 来做到这一点。

所以,我就搜索了一下,没想到。

我可以使用 python 读取规则并将其添加到 Windows 防火墙吗?

windows python-2.7 firewall windows-firewall
2个回答
1
投票

以管理员身份打开Python IDLE或以管理员身份打开CMD并加载python。目标是在运行程序时您应该拥有管理员权限。

def blockrule():
 import os
 c=input('Enter Directory in the format "C:\Program Files (x86)\Common Files\"(without ""): \n')
 d=input('Enter prefix: ')
 e=input('Enter \n"1" for inbound \n"2" for outbound \n"3" for both \nWithout ""\n')
 a=[];b=[]
 for root, dirs, files in os.walk(c):
  for name in files:
   a=a+[[(os.path.join(root,name))]]
 for i in range(len(a)):
  if a[i][0][-3:]=='exe':
   b=b+a[i]
 print('Number of files: '+str(len(a))+'\nNumber of .exe files: '+str(len(b)))
 for i in range (len(b)):
  name=d+str(i)
  if e=='1':
   os.popen('netsh advfirewall firewall add rule name="'+name+'" dir=in action=block program= "'+ b[i]+'" enable=yes profile=any')
  if e=='2':
   os.popen('netsh advfirewall firewall add rule name="'+name+'" dir=out action=block program= "'+ b[i]+'" enable=yes profile=any')
  if e=='3':
   os.popen('netsh advfirewall firewall add rule name="'+name+'" dir=in action=block program= "'+ b[i]+'" enable=yes profile=any')
   os.popen('netsh advfirewall firewall add rule name="'+name+'" dir=out action=block program= "'+ b[i]+'" enable=yes profile=any')

0
投票

并行运行 netsh - 坏主意。

© www.soinside.com 2019 - 2024. All rights reserved.