transHWtoZTEDPI0213

#!/usr/bin/python  
# -*- coding: utf-8 -*-

# -Creat-  : 2019-01-16
# -Author- : 10202373 yk

#1. hw支持掩码可以小于16,需手动检查

import os
import time
import logging
import xml.etree.ElementTree as ET

DomainList = []
DomainDict = {}
DomainId = 1
userProfileList = []
FilterList = []
FilterDict = {}
FilterGrpList = []
FilterGrpDict = {}
L7InfoList = []
L7InfoDict = {}
L7InfoGrpList = []
L7InfoGrpDict = {}
L7RuleList = []
L7RuleDict = {}
RuleList = []
RuleDict = {}
RuleEnrichList = []
CategoryGroupList = []
RuleBindList = []
RuleBindDict = {}
IPListList = []
IpListDict = {}
currentUserProfileName = ''

#global utilize static function
class Utils(object):
    cmdStr = ['user-profile', 'rule-binding', 'host', 'filter', 'filter-group', 'l7-info', 'l7-info-group', 'l7-rule', 'rule', 'rule-enrichment', 'rule-binding', 'category-group','ip-list']

    @staticmethod
    def noNeedProcLine(line):
        #line = line.strip()
        charList = line.split()
        if len(charList) == 0:
            return True
        char = charList[0]
        for cmdChar in Utils.cmdStr:
            if cmp(char.lower(), cmdChar) == 0:
                return False
        return True

    @staticmethod
    def sameIp(ipA, ipB):
        if cmp(ipA, '') == 0 or cmp(ipA, '0.0.0.0') == 0:
            if cmp(ipB, '') == 0 or cmp(ipB, '0.0.0.0') == 0:
                return True
        if cmp(ipA, ipB) == 0:
            return True
        return False

    @staticmethod
    def sameList(listA, listB):
        if len(listA) <> len(listB):
            return False
        for i in range(len(listA)):
            isFind = False
            for j in range(len(listB)):
                if cmp(listA[i], listB[j]) == 0:
                    isFind = True
                    break
            if not isFind:
                return False
        return True

    @staticmethod
    def listContainStr(list, str):
        for strTemp in list:
            if cmp(strTemp, str) == 0:
                return True
        return False
    @staticmethod
    def transUrl(url):
        if len(url) < 3:
            return url
        if cmp(url[-2:], '/*') == 0 and cmp(url[-3:], '*/*') <> 0:
            url = url[:-2]
        if cmp(url[:2], '*.') == 0:
            return url[2:]
        return url

    @staticmethod
    def specialProtocol(protocol):
        if protocol != 'http' and protocol != 'ftp' and protocol != 'rtsp' and protocol != 'connection-wap1.x' and protocol != 'connectionless-wap1.x' and protocol != 'dns':
            return True
        return False

    @staticmethod
    def transProtocol(protocol):
        if protocol == 'http':
            return 'HTTP'
        elif protocol == 'ftp':
            return 'FTP'
        elif protocol == 'rtsp':
            return 'RTSP'
        elif protocol == 'connection-wap1.x' or protocol == 'connectionless-wap1.x':
            return 'WAP1.X'
        elif protocol == 'dns':
            return 'DNS'
        else:
            return 'OTHER'

    # format xml
    @staticmethod
    def indent(elem, level=0):
        i = "\n" + level * "\t"
        if len(elem):
            if not elem.text or not elem.text.strip():
                elem.text = i + "\t"
            if not elem.tail or not elem.tail.strip():
                elem.tail = i
            for elem in elem:
                Utils.indent(elem, level + 1)
            if not elem.tail or not elem.tail.strip():
                elem.tail = i
        else:
            if level and (not elem.tail or not elem.tail.strip()):
                elem.tail = i

class Domain(object):
    def __init__(self):
        self._name_ = ''
        self._domain_ = ''
        self._sequence_ = 0
        self._id_ = 0
    def infoPrint(self):
        print("Domain info name:%s, domain: %s, sequence: %d, id: %d" %
              (self._name_, self._domain_, self._sequence_, self._id_))

class UserProfile(object):
    def __init__(self):
        self._name_ = ''
    def infoPrint(self):
        print("UserProfile info name:%s" % (self._name_))
        
class RuleBind(object):
    def __init__(self):
        self._name_ = ''
        self._priority_ = 0
        self._userProfile_ = ''
    def infoPrint(self):
        print("RuleBind info name:%s, priority=%d, userProfile=%s" % (self._name_, self._priority_, self._userProfile_))

class Filter(object):
    def __init__(self):
        self._name_ = ''
        self._protocol_ = ''
        self._serverIP_ = ''
        self._serverIPMask_ = 0
        self._serverPortS_ = 0
        self._serverPortE_ = 0
        self._msIp_ = ''
        self._msIpMask_ = 0
        self._host_ = ''
        self._sameFilter_ = ''
        self._cate_ = ''
        self._rulebaseid_ = ''
        self._ipList_ = ''

    def isSame(self, oldFilter):
        if cmp(self._host_, oldFilter._host_) == 0 and\
            self._serverIPMask_ == oldFilter._serverIPMask_ and self._serverPortS_ == oldFilter._serverPortS_ and self._serverPortE_ == oldFilter._serverPortE_ and \
            self._msIpMask_ == oldFilter._msIpMask_ and Utils.sameIp(self._serverIP_, oldFilter._serverIP_) and Utils.sameIp(self._msIp_, oldFilter._msIp_):
            return True
        return False

    def subNet(self):

        subIpList = self._serverIP_.split('.')
        if len(subIpList) == 4:
            subIpA = int(subIpList[0])
            subIpB = int(subIpList[1])
            subIpC = int(subIpList[2])
            subIpD = int(subIpList[3])
            subIp = subIpA * 256 * 256 * 256 + subIpB * 256 * 256 + subIpC * 256 + subIpD
            mask = pow(2, 32) - pow(2, (32 - self._serverIPMask_))
            subIpWithMask = subIp & mask
            if subIp == subIpWithMask:
                pass
            else:
                self._serverIP_ = ('%d.%d.%d.%d' % ((subIpWithMask & 0xFF000000) >> 24, (subIpWithMask & 0x00FF0000) >> 16, (subIpWithMask & 0x0000FF00) >> 8, subIpWithMask & 0x000000FF))

    def isDefFilter(self):
        if cmp(self._protocol_, '') == 0 or cmp(self._protocol_, 'any') == 0:
            if cmp(self._serverIP_, '') == 0 and cmp(self._msIp_, '') == 0 and cmp(self._host_, '') == 0:
                if self._serverIPMask_ == 0 and self._serverPortS_ == 0 and self._serverPortE_ == 0 and self._msIpMask_ == 0:
                    return True
        return False

    def infoPrint(self):
        print("Filter info name:%s, protocol=%s, serverIP=%s, serverIPMask=%d, serverPortS=%d, serverPortE=%d, msIp=%s, msIpMask=%d, host=%s, sameFilter=%s, cate=%s, rulebaseid=%s" %
              (self._name_, self._protocol_, self._serverIP_, self._serverIPMask_, self._serverPortS_, self._serverPortE_, self._msIp_, self._msIpMask_, self._host_, self._sameFilter_, self._cate_, self._rulebaseid_))
        
class FilterGrp(object):
    def __init__(self):
        self._name_ = ''
        self._filterName_ = ''
        self._cate_ = ''
    def infoPrint(self):
        print("FilterGrp info name:%s, filterName=%s" %
              (self._name_, self._filterName_))

class L7Info(object):
    def __init__(self):
        self._name_ = ''
        self._url_ = ''
        self._method_ = ''
        self._mediaType_ = ''
        self._l7CategoryGroup_ = ''
    def infoPrint(self):
        print("L7Info info name:%s, url=%s, method=%s, mediaType=%s, l7CategoryGroup=%s" % (self._name_, self._url_, self._method_, self._mediaType_, self._l7CategoryGroup_))
        
class L7InfoGrp(object):
    def __init__(self):
        self._name_ = ''
        self._l7Info_ = ''
        self._priority_ = 0
    def infoPrint(self):
        print("L7InfoGrp info name:%s, l7Info=%s, priority=%d" %
              (self._name_, self._l7Info_, self._priority_))
        
class L7Rule(object):
    def __init__(self):
        self._name_ = ''
        self._protocol_ = ''
        self._protocolGrp_ = ''
        self._l7InfoGroup_ = ''
        self._priority_ = 0
        self._sigCateGrp_ = ''
        self._sigAssoc_ = ''
        self._nonSpecific_ = False
        self._categoryGrp_ = ''

    def infoPrint(self):
        print("L7Rule info name:%s, protocol=%s, l7infogroup=%s, priority=%d, sigCateGrp=%s, sigAssoc=%s, nonSpecific=%d, categoryGrp=%s, protocolGrp=%s" %
              (self._name_, self._protocol_, self._l7InfoGroup_, self._priority_, self._sigCateGrp_, self._sigAssoc_, self._nonSpecific_, self._categoryGrp_, self._protocolGrp_))

class Rule(object):
    def __init__(self):
        self._name_ = ''
        self._filterGrp_ = ''
        self._cateGrp_ = ''
        self._exAction_ = ''
        self._l7Rule_ = ''
        self._priority_ = 0
        self._headEnrich_ = ''
    def hasL7Rule(self):
        if cmp(self._l7Rule_, '') == 0:
            return False
        return True
    def infoPrint(self):
        print("Rule info name:%s, filterGrp=%s, cateGrp=%s, exAction=%s, l7Rule=%s, priority=%d, headEnrich=%s" %
             (self._name_, self._filterGrp_, self._cateGrp_, self._exAction_, self._l7Rule_, self._priority_, self._headEnrich_))

class RuleEnrich(object):
    def __init__(self):
        self._name_ = ''
        self._headEnrich_ = ''
    def infoPrint(self):
        print("RuleEnrich info name:%s, headEnrich=%s" %
              (self._name_, self._headEnrich_))

class CateGrp(object):
    def __init__(self):
        self._name_ = ''
        self._cateProp_ = ''
        self._chagProp_ = ''
        self._actProp_ = ''

    def infoPrint(self):
        print("CategoryGroup info categoryGroup:%s, categoryProperty=%s, chargeProperty=%s, actionProperty=%s" %
              (self._name_, self._cateProp_, self._chagProp_, self._actProp_))

class IpList(object):
    def __init__(self):
        self._name_ = ''
        self._ip_ = ''
        self._mask_ = ''
        self._ipMask_ = ''

    def subNet(self):
        subIpList = self._ip_.split('.')
        if len(subIpList) == 4:
            subIpA = int(subIpList[0])
            subIpB = int(subIpList[1])
            subIpC = int(subIpList[2])
            subIpD = int(subIpList[3])
            subIp = subIpA * 256 * 256 * 256 + subIpB * 256 * 256 + subIpC * 256 + subIpD
            mask = pow(2, 32) - pow(2, (32 - int(self._mask_)))
            subIpWithMask = subIp & mask
            if subIp == subIpWithMask:
                pass
            else:
                self._ip_ = ('%d.%d.%d.%d' % ((subIpWithMask & 0xFF000000) >> 24, (subIpWithMask & 0x00FF0000) >> 16, (subIpWithMask & 0x0000FF00) >> 8, subIpWithMask & 0x000000FF))

    def infoPrint(self):
        print("IpList info name:%s, ipMask:%s" % (self._name_, self._ipMask_))

class FilterBindL7Rule(object):
    def __init__(self):
        self._filterName_ = ''
        self._bindL7RuleNum_ = 0
        self._bindL7Rule_ = []

class Line(object):
    def __init__(self, file):
        self._file_ = file

    def domainExtract(self, charList):
        global DomainId
        global DomainList
        global DomainDict
        length = len(charList)
        index = 0
        newDomain = Domain()
        while index < length:
            if cmp(charList[index], 'host') == 0:
                index = index + 1
                newDomain._name_ = charList[index]
            elif cmp(charList[index], 'domain') == 0:
                index = index + 1
                newDomain._domain_ = charList[index]
            elif cmp(charList[index], 'sequence') == 0:
                index = index + 1
                newDomain._sequence_ = int(charList[index])
            index = index + 1
        if not DomainDict.has_key(newDomain._name_):
            DomainDict[newDomain._name_] = DomainId
            newDomain._id_ = DomainId
            DomainId = DomainId + 1
        #newDomain.infoPrint()
        DomainList.append(newDomain)
    
    def userProfileExtract(self, charList):
        global  currentUserProfileName
        length = len(charList)
        index = 0
        newUserProfile = UserProfile()
        while index < length:
            if cmp(charList[index], 'user-profile') == 0:
                index = index + 1
                newUserProfile._name_ = charList[index]
                currentUserProfileName = charList[index]
            index = index + 1
        #newUserProfile.infoPrint()
        userProfileList.append(newUserProfile)
        
    def ruleBindExtract(self, charList):
        length = len(charList)
        index = 0
        newRuleBind = RuleBind()
        newRuleBind._userProfile_ = currentUserProfileName
        while index < length:
            if cmp(charList[index], 'rule-binding') == 0:
                index = index + 1
                newRuleBind._name_ = charList[index]
            elif cmp(charList[index], 'priority') == 0:
                index = index + 1
                newRuleBind._priority_ = int(charList[index])
            index = index + 1
        #newRuleBind.infoPrint()
        RuleBindList.append(newRuleBind)
        
    def filterExtract(self, charList):
        length = len(charList)
        index = 0
        newFilter = Filter()
        while index < length:
            if cmp(charList[index], 'filter') == 0:
                index = index + 1
                newFilter._name_ = charList[index]
            elif cmp(charList[index], 'l34-protocol') == 0:
                index = index + 1
                newFilter._protocol_ = charList[index]
            elif cmp(charList[index], 'server-ip') == 0:
                index = index + 1
                newFilter._serverIP_ = charList[index]
                index = index + 1
                newFilter._serverIPMask_ = int(charList[index])
            elif cmp(charList[index], 'ms-ip') == 0:
                index = index + 1
                newFilter._msIp_ = charList[index]
                index = index + 1
                newFilter._msIpMask_ = int(charList[index])
            elif cmp(charList[index], 'server-port') == 0:
                index = index + 1
                portType = charList[index]
                if cmp(portType, 'eq') == 0:
                    index = index + 1
                    port = int(charList[index])
                    newFilter._serverPortS_ = port
                    newFilter._serverPortE_ = port
                elif cmp(portType, 'range') == 0:
                    index = index + 1
                    port = int(charList[index])
                    newFilter._serverPortS_ = port
                    index = index + 1
                    port = int(charList[index])
                    newFilter._serverPortE_ = port
            elif cmp(charList[index], 'host') == 0:
                index = index + 1
                newFilter._host_ = charList[index]
            elif cmp(charList[index], 'ipv6') == 0:
                newFilter._serverIP_ = '::'
                newFilter._msIp_ = '::'
            elif cmp(charList[index], 'server-ip-list') == 0:
                index = index + 1
                newFilter._ipList_ = charList[index]
            index = index + 1
        #newFilter.infoPrint()
        newFilter.subNet()
        if not FilterDict.has_key(newFilter._name_):
            FilterDict[newFilter._name_] = newFilter
        else:
            print('repeat name: %s' % (newFilter._name_))
        FilterList.append(newFilter)

    def filterGrpExtract(self, charList):
        global FilterGrpDict
        length = len(charList)
        index = 0
        newFilterGrp = FilterGrp()
        while index < length:
            if cmp(charList[index], 'filter-group') == 0:
                index = index + 1
                newFilterGrp._name_ = charList[index]
            elif cmp(charList[index], 'filter') == 0:
                index = index + 1
                if index >= length:
                    return
                newFilterGrp._filterName_ = charList[index]
            index = index + 1
        #newFilterGrp.infoPrint()
        if not FilterGrpDict.has_key(newFilterGrp._name_):
            FilterGrpDict[newFilterGrp._name_] = []
            FilterGrpDict[newFilterGrp._name_].append(newFilterGrp._filterName_)
        else:
            FilterGrpDict[newFilterGrp._name_].append(newFilterGrp._filterName_)
        FilterGrpList.append(newFilterGrp)
        
    def l7InfoExtract(self, charList):
        length = len(charList)
        index = 0
        newL7Info = L7Info()
        while index < length:
            if cmp(charList[index], 'l7-info') == 0:
                index = index + 1
                newL7Info._name_ = charList[index]
            elif cmp(charList[index], 'url') == 0 or cmp(charList[index], 'host') == 0:
                index = index + 1
                newL7Info._url_ = charList[index]
            elif cmp(charList[index], 'method') == 0:
                index = index + 1
                newL7Info._method_ = charList[index]
            elif cmp(charList[index], 'media-type') == 0:
                index = index + 1
                newL7Info._mediaType_ = charList[index]
            elif cmp(charList[index], 'l7-category-group') == 0:
                index = index + 1
                newL7Info._l7CategoryGroup_ = charList[index]
            index = index + 1
        if not L7InfoDict.has_key(newL7Info._name_):
            L7InfoDict[newL7Info._name_] = newL7Info
        #newL7Info.infoPrint()
        L7InfoList.append(newL7Info)
        
    def l7InfoGrpExtract(self, charList):
        length = len(charList)
        index = 0
        newL7InfoGrp = L7InfoGrp()
        while index < length:
            if cmp(charList[index], 'l7-info-group') == 0:
                index = index + 1
                newL7InfoGrp._name_ = charList[index]
            elif cmp(charList[index], 'l7-info') == 0:
                index = index + 1
                newL7InfoGrp._l7Info_ = charList[index]
            elif cmp(charList[index], 'sequence') == 0:
                index = index + 1
                newL7InfoGrp._priority_ = int(charList[index])
            index = index + 1
        #newL7InfoGrp.infoPrint()
        if not L7InfoGrpDict.has_key(newL7InfoGrp._name_):
            L7InfoGrpDict[newL7InfoGrp._name_] = []
            L7InfoGrpDict[newL7InfoGrp._name_].append(newL7InfoGrp)
        else:
            L7InfoGrpDict[newL7InfoGrp._name_].append(newL7InfoGrp)
        L7InfoGrpList.append(newL7InfoGrp)
        
    def l7RuleExtract(self, charList):
        length = len(charList)
        index = 0
        newL7Rule = L7Rule()
        while index < length:
            if cmp(charList[index], 'l7-rule') == 0:
                index = index + 1
                newL7Rule._name_ = charList[index]
            elif cmp(charList[index], 'protocol') == 0:
                index = index + 1
                newL7Rule._protocol_ = charList[index]
            elif cmp(charList[index], 'l7-info-group') == 0:
                index = index + 1
                newL7Rule._l7InfoGroup_ = charList[index]
            elif cmp(charList[index], 'priority') == 0:
                index = index + 1
                newL7Rule._priority_ = int(charList[index])
            elif cmp(charList[index], 'signaling-category-group') == 0:
                index = index + 1
                newL7Rule._sigCateGrp_ = charList[index]
            elif cmp(charList[index], 'signaling-associate') == 0:
                index = index + 1
                newL7Rule._sigAssoc_ = charList[index]
            elif cmp(charList[index], 'non-specific') == 0:
                newL7Rule._nonSpecific_ = True
            elif cmp(charList[index], 'category-group') == 0:
                index = index + 1
                newL7Rule._categoryGrp_ = charList[index]
            elif cmp(charList[index], 'protocol-group') == 0:
                index = index + 1
                newL7Rule._protocolGrp_ = charList[index]
            index = index + 1
        #newL7Rule.infoPrint()
        if not L7RuleDict.has_key(newL7Rule._name_):
            L7RuleDict[newL7Rule._name_] = []
            L7RuleDict[newL7Rule._name_].append(newL7Rule)
        else:
            L7RuleDict[newL7Rule._name_].append(newL7Rule)
        L7RuleList.append(newL7Rule)

    def ruleExtract(self, charList):
        length = len(charList)
        index = 0
        newRule = Rule()
        while index < length:
            if cmp(charList[index], 'rule') == 0:
                index = index + 1
                newRule._name_ = charList[index]
            elif cmp(charList[index], 'filter-group') == 0:
                index = index + 1
                newRule._filterGrp_ = charList[index]
            elif cmp(charList[index], 'service-category-group') == 0:
                index = index + 1
                newRule._cateGrp_ = charList[index]
            elif cmp(charList[index], 'extension-action') == 0:
                index = index + 1
                newRule._exAction_ = charList[index]
            elif cmp(charList[index], 'l7-rule') == 0:
                index = index + 1
                newRule._l7Rule_ = charList[index]
            elif cmp(charList[index], 'priority') == 0:
                index = index + 1
                newRule._priority_ = int(charList[index])
            index = index + 1
        #newRule.infoPrint()
        if not RuleDict.has_key(newRule._name_):
            RuleDict[newRule._name_] = newRule
        RuleList.append(newRule)

    def ruleEnrichExtract(self, charList):
        length = len(charList)
        index = 0
        newRuleEnrich = RuleEnrich()
        while index < length:
            if cmp(charList[index], 'rule') == 0:
                index = index + 1
                newRuleEnrich._name_ = charList[index]
            elif cmp(charList[index], 'header-enrichment') == 0:
                index = index + 1
                newRuleEnrich._headEnrich_ = charList[index]
            index = index + 1
        #newRuleEnrich.infoPrint()
        RuleEnrichList.append(newRuleEnrich)

    def cateGroupExtract(self, charList):
        length = len(charList)
        index = 0
        newCateGrp = CateGrp()
        while index < length:
            if cmp(charList[index], 'category-group') == 0:
                index = index + 1
                newCateGrp._name_ = charList[index]
            elif cmp(charList[index], 'category-property') == 0:
                index = index + 1
                newCateGrp._cateProp_ = charList[index]
            elif cmp(charList[index], 'charge-property') == 0:
                index = index + 1
                newCateGrp._chagProp_ = charList[index]
            elif cmp(charList[index], 'action-property') == 0:
                index = index + 1
                newCateGrp._actProp_ = charList[index]
            index = index + 1
        #newCateGrp.infoPrint()
        CategoryGroupList.append(newCateGrp)

    def ipListExtract(self, charList):
        length = len(charList)
        index = 0
        newIpList = IpList()
        while index < length:
            if cmp(charList[index], 'ip-list') == 0:
                index = index + 1
                if cmp(charList[index], 'ipv6') == 0:
                    index = index + 1
                newIpList._name_ = charList[index]
                index = index + 1
                if cmp(charList[index], 'ipv6') == 0:
                    index = index + 1
                newIpList._ipMask_ = charList[index]
            index = index + 1
        newIpList._ip_ = newIpList._ipMask_.split('/')[0]
        newIpList._mask_ = newIpList._ipMask_.split('/')[1]
        newIpList.subNet()
        if not IpListDict.has_key(newIpList._name_):
            IpListDict[newIpList._name_] = []
            IpListDict[newIpList._name_].append(newIpList)
        else:
            IpListDict[newIpList._name_].append(newIpList)
        IPListList.append(newIpList)
        #newIpList.infoPrint()

    def lineProc(self, line):
        charList = line.split()
        keyChar = charList[0]
        if cmp(keyChar, 'user-profile') == 0:
            self.userProfileExtract(charList)
        elif cmp(keyChar, 'host') == 0:
            self.domainExtract(charList)
        elif cmp(keyChar, 'filter') == 0:
            self.filterExtract(charList)
        elif cmp(keyChar, 'filter-group') == 0:
            self.filterGrpExtract(charList)
        elif cmp(keyChar, 'l7-info') == 0:
            self.l7InfoExtract(charList)
        elif cmp(keyChar, 'l7-info-group') == 0:
            self.l7InfoGrpExtract(charList)
        elif cmp(keyChar, 'l7-rule') == 0:
            self.l7RuleExtract(charList)
        elif cmp(keyChar, 'rule') == 0:
            self.ruleExtract(charList)
        elif cmp(keyChar, 'rule-enrichment') == 0:
            self.ruleEnrichExtract(charList)
        elif cmp(keyChar, 'rule-binding') == 0:
            self.ruleBindExtract(charList)
        elif cmp(keyChar, 'category-group') == 0:
            self.cateGroupExtract(charList)
        elif cmp(keyChar, 'ip-list') == 0:
            self.ipListExtract(charList)
    def proc(self):
        line = self._file_.readline()
        while line:
            line = line.strip()
            if Utils.noNeedProcLine(line):
                line = self._file_.readline()
                continue
            self.lineProc(line)
            line = self._file_.readline()

#domain config
def dpiRuleWriteDns(dns):
    global DomainList
    for domain in DomainList:
        dnsRuleDict = {}
        dnsRuleDict['name'] = domain._name_
        dnsRuleDict['domainname'] = domain._domain_
        dnsRuleDict['domainid'] = str(domain._id_)
        dnsRuleDict['domaintype'] = "1"
        ET.SubElement(dns, 'dnsrule', dnsRuleDict)
        #domain.infoPrint()

#write fix xml emlment
def dpiRuleWriteFixed(globalconfig):
    enrichfraudlist = ET.SubElement(globalconfig, 'enrichfraudlist')
    enrichfraudlistRule = {'name':'IMSI', 'fraudstring':'IMSI'}
    ET.SubElement(enrichfraudlist, 'enrichfraudlistRule', enrichfraudlistRule)
    enrichfraudlistRule = {'name': 'MSISDN', 'fraudstring': 'MSISDN'}
    ET.SubElement(enrichfraudlist, 'enrichfraudlistRule', enrichfraudlistRule)
    enrichfraudlistRule = {'name': 'RATTYPE', 'fraudstring': 'RATTYPE'}
    ET.SubElement(enrichfraudlist, 'enrichfraudlistRule', enrichfraudlistRule)
    enrichfraudlistRule = {'name': 'Accept', 'fraudstring': 'Accept'}
    ET.SubElement(enrichfraudlist, 'enrichfraudlistRule', enrichfraudlistRule)

    switch = ET.SubElement(globalconfig, 'switch')
    urlruleDict = {'urlopt':'Disable', 'groupextend':'Disable'}
    ET.SubElement(switch, 'urlrule', urlruleDict)

    option = ET.SubElement(globalconfig, 'option')
    optionruleDict = {'option1':'optimization-2'}
    ET.SubElement(option, 'optionrule', optionruleDict)

#default dns rule set
#domain match need config dns rule
def dpiRuleWriteDefDns(template):
    l4ruleDict = {'name': 'defDns', 'apptype': 'DNS'}
    l4rule = ET.SubElement(template, 'l4rule', l4ruleDict)
    l4conditionset = ET.SubElement(l4rule, 'l4conditionset')
    l4conditionDict = {}
    l4conditionDict['name'] = 'defDns'
    l4conditionDict['sourceip'] = '0.0.0.0'
    l4conditionDict['sourceipmask'] = '0'
    l4conditionDict['destip'] = '0.0.0.0'
    l4conditionDict['destipmask'] = '0'
    l4conditionDict['transtype'] = 'UDP'
    l4conditionDict['sourcestartport'] = '0'
    l4conditionDict['sourceendport'] = '0'
    l4conditionDict['deststartport'] = '53'
    l4conditionDict['destendport'] = '53'
    l4conditionDict['rulebaseid'] = '111111111'
    l4conditionDict['xDPI'] = '0'
    l4conditionDict['acctmode'] = 'ANY'
    l4conditionDict['freeFlg'] = 'Not Free'
    ET.SubElement(l4conditionset, 'l4condition', l4conditionDict)

#write only template
def dpiRuleWriteTemp(dpiconfig):
    templateDict = {'id': '100', 'name': 'onlyTemplate', 'acctmode': 'associated with Service Mode'}
    template = ET.SubElement(dpiconfig, 'template', templateDict)
    default = ET.SubElement(template, 'default')
    default_v4Dict = {'name': 'default', 'rulebaseid': '100000000', 'xDPI': '1', 'alias': 'DEF-PASS',
                      'freeFlg': 'Not Free', 'position': '1', 'acctmode': 'ANY'}
    ET.SubElement(default, 'default_v4', default_v4Dict)
    dpiRuleWriteDefDns(template)
    global  RuleBindDict
    for key in RuleBindDict.keys():
        ruleBind = RuleBindDict[key]
        ruleName = ruleBind._name_
        rule = RuleDict[ruleName]
        l34FilterGrpName = rule._filterGrp_
        l7FilterGrpName = rule._l7Rule_
        l34FilterGrpCateGrp = rule._cateGrp_
        onlyL34 = False
        xdpiOpen = False
        hwappType = ''   #protocol
        if l7FilterGrpName == '':
            onlyL34 = True
        else :
            l7RuleList = L7RuleDict[l7FilterGrpName]        #binding l7 rule object list
            #get xdpi switch
            for l7Rule in l7RuleList:
                if (l7Rule._protocolGrp_ != '' and l7Rule._protocol_ == '') or (l7Rule._protocol_ != '' and  Utils.specialProtocol(l7Rule._protocol_)):
                    xdpiOpen = True
                    break
            #get apptype
            hasNormalApptype = False
            for l7Rule in l7RuleList:
                if l7Rule._protocol_ != '' and not Utils.specialProtocol(l7Rule._protocol_):
                    hasNormalApptype = True
                    hwappType = l7Rule._protocol_
            if not hasNormalApptype:
                onlyL34 = True
        if l34FilterGrpName != '':
            l34FilterList = FilterGrpDict[l34FilterGrpName]   #l34filter name list(相同的rule)
            if len(l34FilterList) == 0:
                continue
        else:
            continue
        global FilterDict
        if len(l34FilterList) > 0:
            l4ruleDict = {}
            l4ruleDict['name'] = ruleName
            if hwappType != '':
                apptype = Utils.transProtocol(hwappType)
                l4ruleDict['apptype'] = apptype
            else:
                l4ruleDict['apptype'] = 'OTHER'
        l4rule = ET.SubElement(template, 'l4rule', l4ruleDict)
        l4conditionset = ET.SubElement(l4rule, 'l4conditionset')
        for l34FilterName in l34FilterList:
            l34Filter = FilterDict[l34FilterName]
            if len(l34Filter._ipList_) == 0: #   例如 filter any l34-protocol any   配默认
                l4conditionDict = {}
                l4conditionDict['name'] = l34Filter._name_
                l4conditionDict['sourceip'] = '0.0.0.0' if cmp(l34Filter._msIp_, '') == 0 else l34Filter._msIp_
                l4conditionDict['sourceipmask'] = str(l34Filter._msIpMask_)
                if len(l34Filter._host_) == 0:
                    l4conditionDict['destip'] = '0.0.0.0' if cmp(l34Filter._serverIP_, '') == 0 else l34Filter._serverIP_
                    # l4conditionDict['destipmask'] = str(l34Filter._serverIPMask_) if l34Filter._serverIPMask_ >= 16 else (
                    # '16' if cmp(l4conditionDict['destip'], '0.0.0.0') <> 0 else '0')
                    l4conditionDict['destipmask'] = str(l34Filter._serverIPMask_)
                else:
                    l4conditionDict['destdomain'] = str(DomainDict[l34Filter._host_])
                l4conditionDict['transtype'] = ('TCP' if cmp(l34Filter._protocol_, '') == 0 else l34Filter._protocol_).upper()
                l4conditionDict['sourcestartport'] = '0'
                l4conditionDict['sourceendport'] = '0'
                l4conditionDict['deststartport'] = str(l34Filter._serverPortS_)
                l4conditionDict['destendport'] = str(l34Filter._serverPortE_)
                l4conditionDict['rulebaseid'] = l34FilterGrpCateGrp
                l4conditionDict['xDPI'] = '0'
                if xdpiOpen:
                    l4conditionDict['xDPI'] = '1'
                l4conditionDict['acctmode'] = 'ANY'
                l4conditionDict['freeFlg'] = 'Not Free'
                ET.SubElement(l4conditionset, 'l4condition', l4conditionDict)
            else:
                ipListName = l34Filter._ipList_
                ipList = IpListDict[ipListName]
                ipIndex = 0
                for ip in ipList:
                    l4conditionDict = {}
                    l4conditionDict['name'] = l34Filter._name_ + '_Num_' + str(ipIndex)
                    ipIndex = ipIndex + 1
                    l4conditionDict['sourceip'] = '0.0.0.0' if cmp(l34Filter._msIp_, '') == 0 else l34Filter._msIp_
                    l4conditionDict['sourceipmask'] = str(l34Filter._msIpMask_)
                    l4conditionDict['destip'] = '0.0.0.0' if cmp(ip._ip_, '') == 0 else ip._ip_
                    l4conditionDict['destipmask'] = str(ip._mask_)
                    l4conditionDict['transtype'] = ('any' if cmp(l34Filter._protocol_, '') == 0 else l34Filter._protocol_).upper()
                    l4conditionDict['sourcestartport'] = '0'
                    l4conditionDict['sourceendport'] = '0'
                    l4conditionDict['deststartport'] = str(l34Filter._serverPortS_)
                    l4conditionDict['destendport'] = str(l34Filter._serverPortE_)
                    l4conditionDict['rulebaseid'] = l34FilterGrpCateGrp
                    l4conditionDict['xDPI'] = '0'
                    if xdpiOpen:
                        l4conditionDict['xDPI'] = '1'
                    l4conditionDict['acctmode'] = 'ANY'
                    l4conditionDict['freeFlg'] = 'Not Free'
                    ET.SubElement(l4conditionset, 'l4condition', l4conditionDict)

        if onlyL34:
            continue
        l7ruleset = ET.SubElement(l4rule, 'l7ruleset')
        global L7InfoGrpDict
        global L7InfoDict
        for l7Rule in l7RuleList:
            if l7Rule._protocol_ != '' and not Utils.specialProtocol(l7Rule._protocol_):
                if l7Rule._l7InfoGroup_ == '':
                    continue
                l7InfoGrpName = l7Rule._l7InfoGroup_
                l7InfoGrpList = L7InfoGrpDict[l7InfoGrpName]
                for l7InfoGrp in l7InfoGrpList:
                    l7InfoName = l7InfoGrp._l7Info_
                    prority = str(l7InfoGrp._priority_)
                    l7Info = L7InfoDict[l7InfoName]
                    l7infoDict = {}
                    l7infoDict['name'] = l7Info._name_
                    l7infoDict['url'] = l7Info._url_
                    l7infoDict['rulebaseid'] = l7Info._l7CategoryGroup_
                    l7infoDict['priority'] = '0'
                    l7infoDict['method'] = 'ANY'
                    l7infoDict['servicetype'] = 'OTHER'
                    l7infoDict['freeFlg'] = 'Not Free'
                    l7infoDict['proxy'] = 'ANY'
                    ET.SubElement(l7ruleset, 'l7rule', l7infoDict)

#write rule
def dpiRuleWrite():
    dpiconfig = ET.Element('dpiconfig')
    globalDict = {'engineversion':'ZXUN xGW(GUL)V5.17.12.B11', 'modifyversion':'2018-12-31 23:59:59', 'modifytime':'2018-12-31 23:59:59', 'username':'dpitool','tooltype':'GUI Tool','xGWdpifiletype':'GSU'}
    ET.SubElement(dpiconfig, 'global', globalDict)
    globalconfig = ET.SubElement(dpiconfig, 'globalconfig')
    dns = ET.SubElement(globalconfig, 'dns')
    dpiRuleWriteDns(dns)
    dpiRuleWriteFixed(globalconfig)
    dpiRuleWriteTemp(dpiconfig)
    Utils.indent(dpiconfig)
    tree = ET.ElementTree(dpiconfig)
    tree.write("malaixiya.xml")

def ruleToDpi():
    global userProfileList
    global RuleBindList
    global RuleBindDict
    #rule的去重
    for ruleBind in RuleBindList:
        if not RuleBindDict.has_key(ruleBind._name_):
            RuleBindDict[ruleBind._name_] = ruleBind
            #print ruleBind._name_
    dpiRuleWrite()

if __name__=="__main__":
    confFilePath = os.getcwd()
    files = os.listdir(confFilePath)
    findCfgFile = False
    for file in files:
        if cmp(os.path.splitext(file)[len(os.path.splitext(file)) - 1], '.cfg') == 0 or cmp(os.path.splitext(file)[len(os.path.splitext(file)) - 1], '.log') == 0:
        #if (os.path.splitext(file)[len(os.path.splitext(file)) - 1]).find('cfg') != -1:
            cfgFile = file
            findCfgFile = True
            break
    if not findCfgFile:
        print('this dir has not show running cfg file, please copy show running cfg file to this dir!')
        exit(1)
    cfgFile = open(os.path.join(confFilePath, cfgFile), 'r')
    line = Line(cfgFile)
    line.proc()
    ruleToDpi()
    cfgFile.close()
    exit(1)

猜你喜欢

转载自blog.csdn.net/u014686859/article/details/87338616