分享一個Python寫的windows環境系統服務來自動化管理防火牆規則

專注的阿熊發表於2022-01-04

import pythoncom

import win32com

class rule:

     items = {}

     # 中英文轉換

     items_name = {

         "Action":' 操作 ',

         "ApplicationName":' 程式 ',

         "Description":' 描述 ',

         "Direction":' 進站 / 出站 ',

         "EdgeTraversal":' 邊緣穿越 ',

         "EdgeTraversalOptions":' 邊緣穿越選項 ',

         "Enabled":' 已啟用 ',

         "Grouping":' ',

         "IcmpTypesAndCodes":'ICMP 設定 ',

         "InterfaceTypes":' 介面型別 ',

         "Interfaces":' 介面 ',

         "LocalAddresses":' 本地地址 ',

         "LocalAppPackageId":' 應用程式包 ',

         "LocalPorts":' 本地埠 ',

         "LocalUserAuthorizedList":' 授權的本地計算機 ',

         "LocalUserOwner":' 本地使用者所有者 ',

         "Name":' 名稱 ',

         "Profiles":' 配置檔案 ',

         "Protocol":' 協議 ',

         "RemoteAddresses":' 遠端地址 ',

         "RemoteMachineAuthorizedList":' 授權的遠端計算機 ',

         "RemotePorts":' 遠端埠 ',

         "RemoteUserAuthorizedList":' 授權的遠端使用者 ',

         "SecureFlags":' 安全 ',

         "serviceName":' 服務名 '}

     items_shell = {

         "Action": 'action',

         "ApplicationName": 'program',

         "Description": 'description',

         "Direction": 'dir',

         "EdgeTraversal": 'edge',

         "EdgeTraversalOptions": ' 邊緣穿越選項 ',

         "Enabled": 'enable',

         "Grouping": ' ',

         "IcmpTypesAndCodes": 'ICMP 設定 ',

         "InterfaceTypes": 'interfacetype',

         "Interfaces": ' 介面 ',

         "LocalAddresses": 'localip',

         "LocalAppPackageId": ' 應用程式包 ',

         "LocalPorts": 'localport',

         "LocalUserAuthorizedList": ' 授權的本地計算機 ',

         "LocalUserOwner": ' 本地使用者所有者 ',

         "Name": 'name',

         "Profiles": 'profile',

         "Protocol": 'protocol',

         "RemoteAddresses": 'remoteip',

         "RemoteMachineAuthorizedList": 'rmtcomputergrp',

         "RemotePorts": 'remoteport',

         "RemoteUserAuthorizedList": 'rmtusrgrp',

         "SecureFlags": 'security',

         "serviceName": 'service'

     }

     def __init__(self,index):

         self.index = index

         for i in self.items_name.keys():

             self.items[i] = ''

     def init_by_app(self, app_in):

         for key in self.items_name.keys():

             self.items[key] = " " + str(eval("app_in."+key))

             print(self.items[key] )

     def init_by_dict(self,dirc_con):

         flag = False

         for item_key in self.items_name.keys():

             if self.items_name[item_key] in dirc_con.keys():

                 flag = True

                 self.items[item_key] = dirc_con[self.items_name[item_key]]

         if not flag:

             for key in dirc_con.keys():

                 self.items[key] = dirc_con[key]

     def create_rule(self):

         app = win32com.client.Dispatch('HNetCfg.FwRule')

         res = []

         # 注意賦值順序

         app.Action = int(self.items["Action"])

         app.Description = self.items["Description"]

         app.Direction = int(self.items["Direction"])

         app.EdgeTraversal = self.items["EdgeTraversal"]

         app.EdgeTraversalOptions = self.items["EdgeTraversalOptions"]

         app.Enabled = self.items["Enabled"]

         app.Grouping = self.items["Grouping"]

         ## app.IcmpTypesAndCodes = self.items["IcmpTypesAndCodes"]

         app.InterfaceTypes = self.items["InterfaceTypes"]

         ## app.Interfaces = self.items["Interfaces"]

         app.LocalAddresses = self.items["LocalAddresses"]

         app.LocalAppPackageId = self.items["LocalAppPackageId"]

         ## app.LocalPorts = str(self.items["LocalPorts"]),

         ## app.LocalUserAuthorizedList = self.items["LocalUserAuthorizedList"]

         app.LocalUserOwner = self.items["LocalUserOwner"]

         app.Name = self.items["Name"]

         app.Profiles = self.items["Profiles"]

         app.Protocol = self.items["Protocol"]

         app.RemoteAddresses = self.items["RemoteAddresses"]

         ## app.RemoteMachineAuthorizedList = self.items["RemoteMachineAuthorizedList"]

         app.RemotePorts = self.items["RemotePorts"]

         app.LocalPorts = self.items['LocalPorts']

         ## app.RemoteUserAuthorizedList = ''

         app.SecureFlags = self.items["SecureFlags"]

         # app.serviceName = "null"

         # app.ApplicationName = "null"

         return app

     def __str__(self):

         result = "="*10 + '\n 序號 : ' + str(self.index) + '\n'

         for key in self.items_name.keys():

             result += self.items_name[key] + " : " + str(self.items[key]) +"\n"

         return result

def add_rule(dict_value):

     fw = win32com.client.gencache.EnsureDispatch('HNetCfg.FwPolicy2', 0)

     apps = fw.Rules

     print(apps.Count)

     # app = win32com.client.Dispatch('HNetCfg.FwRule3')

     rule_obj = rule(-1)

     rule_obj.init_by_dict(dict_value)

     app = rule_obj.create_rule()

     apps.Add(app)

def del_rule(dict_value):

     fw = win32com.client.gencache.EnsureDispatch('HNetCfg.FwPolicy2', 0)

     apps = fw.Rules

     print("before :", apps.Count)

     rule_obj = rule(-1)

     rule_obj.init_by_dict(dict_value)

     for app in apps:

         print(rule_obj.items['Name'] , str(app.Name))

         print(rule_obj.items['LocalPorts'] , str(app.LocalPorts))

         print(rule_obj.items['RemoteAddresses'] , str(app.RemoteAddresses))

         if rule_obj.items['Name']外匯跟單gendan5.com == str(app.Name) and rule_obj.items['LocalPorts'] == str(app.LocalPorts) and rule_obj.items['RemoteAddresses'] == str(app.RemoteAddresses):

             # 只能根據 Name 刪除 , 大概是個傻子喲

             apps.Remove(str(app.Name))

             # break

     print("after :", apps.Count)

if __name__ == '__main__':

     my_dict = {

     ' 序號 ' : '2',

     ' 操作 ' : '0',

     ' 程式 ' : '',

     ' 描述 ' : '',

     ' 進站 / 出站 ' : '1',

     ' 邊緣穿越 ' : 'False',

     ' 邊緣穿越選項 ' : '0',

     ' 已啟用 ' : 'True',

     ' ' : '',

     'ICMP 設定 ' : '',

     ' 介面型別 ' : 'All',

     ' 介面 ' : 'None',

     ' 本地地址 ' : '*',

     ' 應用程式包 ' : '',

     ' 本地埠 ' : '9876',

     ' 授權的本地計算機 ' : '',

     ' 本地使用者所有者 ' : '',

     ' 名稱 ' : 'test_cmd',

     ' 配置檔案 ' : '2',

     ' 協議 ' : '6',

     ' 遠端地址 ' : '114.115.250.41/255.255.255.255',

     ' 授權的遠端計算機 ' : '',

     ' 遠端埠 ' : '*',

     ' 授權的遠端使用者 ' : '',

     ' 安全 ' : '0',

     ' 服務名 ' : ''

     }

     add_rule(my_dict)

     del_rule(my_dict)


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69946337/viewspace-2850616/,如需轉載,請註明出處,否則將追究法律責任。

相關文章