简体   繁体   English

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

[英]How to Read and Add Rules in Windows Firewall with Python

I'm creating a service that needs to constantly monitor the Firewall to prevent unsuspecting users from removing the doors of a service.我正在创建一个需要不断监控防火墙的服务,以防止毫无戒心的用户移除服务的大门。 My intention is to do this using python.我的意图是使用 python 来做到这一点。

So, I searched for it and did not think.所以,我搜索它并没有考虑。

can I read and add rules to Windows Firewall using python?我可以使用python 读取规则并将规则添加到Windows 防火墙吗?

Open Python IDLE as an administrator or CMD as administrator and load python.以管理员身份打开 Python IDLE 或以管理员身份打开 CMD 并加载 python。 Aim is so that while running the program you should have administrator privilege.目的是在运行程序时您应该拥有管理员权限。

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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM