Ejemplo n.º 1
0
def cron_bak():
    assets = Assets.objects.all()
    logger.info("开始备份任务")
    for asset in assets:
        if str.lower(asset.manufacturer) == 'h3c' and asset.assets_type in [
                'firewall', 'switch', 'route'
        ]:
            net_asset = Network_Assets.objects.get(assets_id=asset.id)
            if net_asset.passwd and net_asset.username:
                bak_dev = conf_bak.H3cSW(net_asset.hostname, net_asset.ip,
                                         int(net_asset.port),
                                         net_asset.username, net_asset.passwd)
                bak_thread = threading.Thread(bak_dev.conf_bak())
            else:
                logger.warn("%s-的用户名或密码不存在,取消备份", net_asset.hostname)
        elif str.lower(
                asset.manufacturer) == 'ruijie' and asset.assets_type in [
                    'firewall', 'switch', 'route'
                ]:
            net_asset = Network_Assets.objects.get(assets_id=asset.id)
            if net_asset.passwd and net_asset.username:
                bak_dev = conf_bak.RuiJeiSW(net_asset.hostname, net_asset.ip,
                                            int(net_asset.port),
                                            net_asset.username,
                                            net_asset.passwd)
                bak_thread = threading.Thread(bak_dev.conf_bak())
            else:
                logger.warn("%s-的用户名或密码不存在,取消备份", net_asset.hostname)
Ejemplo n.º 2
0
 def to_enable(self):
     self.ssh_connect.send('enable\n')
     time.sleep(1)
     out = self.ssh_connect.recv(1024).decode()
     if "Password:"******"Password:"******"进入enable 失败,请检查密码是否正确")
             exit()
         elif "Ruijie#" in out:
             logger.info("进入enable模式")
Ejemplo n.º 3
0
 def new_ssh_connect(self):
     self.client = paramiko.SSHClient()
     self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
     try:
         self.client.connect(self.ip,
                             self.port,
                             self.user,
                             self.password,
                             timeout=5)
         self.ssh_connect = self.client.invoke_shell()
     except Exception as e:
         logger.info("%s SSH 连接失败,失败原因:%s", self.hostname, e)
         exit()
Ejemplo n.º 4
0
    def conf_bak(self):
        self.new_ssh_connect()
        out = self.ssh_connect.recv(1024).decode()
        self.to_enable()
        logger.info("????................")
        self.ssh_connect.send('copy running-config tftp:\n')
        time.sleep(1)
        out = self.ssh_connect.recv(1024).decode()
        if 'Address of remote host []?' in out:
            logger.info("TFTP Server?172.168.1.17")
            self.ssh_connect.send('172.168.1.17\n')
            time.sleep(1)
            out = self.ssh_connect.recv(1024).decode()
            if 'Destination filename []?' in out:
                date = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
                filename = "ruijie" + date + ".cfg"
                logger.info("备份文件名%s", filename)
                self.ssh_connect.send(filename + '\n')
                time.sleep(1)
                out = self.ssh_connect.recv(1024).decode()
                if "Transmission success" in out:
                    logger.info("%s 备份成功", self.hostname)

        #reout = re.search("(\[(.*?)\][#|$]+)(?P<num>(.*)+)(\[(.*?)\][#|$]+) ", out, re.S)

        self.del_ssh_connect()
Ejemplo n.º 5
0
def anychangenet(srcdev, passdev):
    srcaddrlist = []
    if srcdev.type == 'netaddr':
        srcaddrlist.append(srcdev)
    else:
        for i in Topo.netaddrlist:
            # 遍历源设备到,所有终端地址最短路径,路径中
            if i.name != srcdev.name:
                try:
                    routelist = networkx.shortest_path(Topo.nxtopology,
                                                       source=srcdev,
                                                       target=i)
                except:
                    logger.info(srcdev.name + " to " + i.name + "路径不完整")
                    continue
                if passdev not in routelist:
                    srcaddrlist.append(i)

    return srcaddrlist
Ejemplo n.º 6
0
    def conf_bak(self):

        self.new_ssh_connect()
        time.sleep(1)
        out = self.ssh_connect.recv(1024).decode()
        #fencoding = chardet.detect(out)
        date = datetime.datetime.now().strftime("%Y%m%d")
        filename = self.hostname + "-" + date + ".cfg"
        cmd = "backup startup-configuration to 10.16.17.100 " + filename
        self.ssh_connect.send("\n")
        time.sleep(1)
        self.ssh_connect.send(cmd + "\n")
        time.sleep(5)
        out = self.ssh_connect.recv(65535).decode()
        if 'Finished.' or 'finished!' in out:
            logger.info("%s 备份成功", self.hostname)
        else:
            logger.error("%s 备份失败", self.hostname)
        self.del_ssh_connect()
Ejemplo n.º 7
0
def iszmbiepolicy(checkfirewall):
    zmbiepolicylist = []
    policy_zone = Firewall_Policy_Zone.objects.filter(
        Network_Assets_id=checkfirewall.assetid)
    # 遍历需要检测防火墙的原子策略表
    for checkpoliy in checkfirewall.policymiclist:
        srcdev = ''
        dstdev = ''
        srcnetlist = []
        dstnetlist = []
        logger.info("checkpolcy" + checkpoliy.srceth + " " +
                    checkpoliy.dsteth + " " + checkpoliy.srcaddr + " " +
                    checkpoliy.dstaddr)
        # 不对未初始化的安全域策略检查 设备互联地址
        srcisnetaddr = isnetaddr(checkpoliy.srcaddr)
        dstisnetaddr = isnetaddr(checkpoliy.dstaddr)
        if not srcisnetaddr or not dstisnetaddr:
            # if not srcisnetaddr:
            # logger.debug("地址未在拓扑中添加:" + checkpoliy.srcaddr)
            # if not dstisnetaddr:
            # logger.debug("地址未在拓扑中添加:" + checkpoliy.dstaddr)
            continue
        # 根据策略原&目的地址确定,策略可能经过的源节点设备和目的节点设备
        if checkpoliy.srcaddr == '0.0.0.0/0':
            for port in policy_zone:
                if checkpoliy.srceth == port.zone:
                    srcdev = port.assets_name
            # logger.info('srcdev:' + srcdev)
            for i in Topo.nxtopology.nodes:
                if i.name == srcdev:
                    srcnetlist = anychangenet(i, checkfirewall)
        else:
            srcnet = iplocate(checkpoliy.srcaddr)
            if srcnet != False:
                srcnetlist.append(srcnet)
        if checkpoliy.dstaddr == '0.0.0.0/0':
            for port in policy_zone:
                if checkpoliy.dsteth == port.zone:
                    dstdev = port.assets_name
            for i in Topo.nxtopology.nodes:
                if i.name == dstdev:
                    dstnetlist = anychangenet(i, checkfirewall)
        else:
            dstnet = iplocate(checkpoliy.dstaddr)
            if dstnet != False:
                dstnetlist.append(dstnet)
        logger.info('src:' + checkpoliy.srcaddr)
        logger.info('dst:' + checkpoliy.dstaddr)
        if len(srcnetlist) > 0:
            for i in srcnetlist:
                logger.info('srcnet:' + i.name)
        if len(dstnetlist) > 0:
            for i in dstnetlist:
                logger.info('dstnet:' + i.name)
        # 如果存在源节点设备和目的节点设备
        if len(dstnetlist) > 0 and len(srcnetlist) > 0:
            # 遍历源节点和目的节点设备
            for srcnet in srcnetlist:
                for dstnet in dstnetlist:
                    # 查找源到目的节点的路径
                    try:
                        routelist = networkx.shortest_path(Topo.nxtopology,
                                                           source=srcnet,
                                                           target=dstnet)
                    except:
                        logger.info(srcnet.name + " to " + dstnet.name +
                                    "路径不完整")
                        continue
                    iscontent = 0
                    # 遍历路径设备列表
                    for i in range(len(routelist)):
                        # 设备与策略主机一致跳过

                        if routelist[i] == checkfirewall:
                            continue
                        # 如设备类型为防火墙
                        elif routelist[i].type == 'firewall':
                            logger.info("经过防火墙:" + routelist[i].name)
                            # 根据上下游设备 确定检测策略经过本机的安全域或端口
                            srceth = ''
                            dsteth = ''
                            portlink = Firewall_Policy_Zone.objects.filter(
                                Network_Assets_id=routelist[i].assetid)
                            for port in portlink:
                                if routelist[i - 1].name in port.assets_name:
                                    srceth = port.zone
                                if routelist[i + 1].name in port.assets_name:
                                    dsteth = port.zone
                            logger.info('srceth:' + srceth + ' ' + 'dsteth:' +
                                        dsteth)
                            # 遍历主机原子策略表,与经过的安全域策略比较是否有相应的策略
                            for j in routelist[i].policymiclist:
                                if j.srceth == srceth and j.dsteth == dsteth:
                                    iscontent = 1
                                    if IPy.IP(checkpoliy.srcaddr).overlaps(
                                            j.srcaddr) == 1 or IPy.IP(
                                                j.srcaddr).overlaps(
                                                    checkpoliy.srcaddr) == 1:

                                        if IPy.IP(checkpoliy.dstaddr).overlaps(
                                                j.dstaddr
                                        ) == 1 or IPy.IP(j.dstaddr).overlaps(
                                                checkpoliy.dstaddr) == 1:
                                            if checkpoliy.service[
                                                    'protocol'] == '0' or j.service[
                                                        'protocol'] == '0':
                                                # print("-----------------------匹配---------------------------------------")
                                                # print(routelist[i].name)
                                                # checkpoliy.printpolicymic()
                                                # j.printpolicymic()
                                                iscontent = 2
                                                break
                                            # 不对ping操作做报文类型比较 部分防火墙对ICMP做了分类可能造成匹配不精确
                                            elif checkpoliy.service[
                                                    'protocol'] == '1' or j.service[
                                                        'protocol'] == '1':
                                                # print("-----------------------匹配---------------------------------------")
                                                # print(routelist[i].name)
                                                # checkpoliy.printpolicymic()
                                                # j.printpolicymic()
                                                iscontent = 2
                                                break
                                            elif checkpoliy.service[
                                                    'port'] == j.service[
                                                        'port'] and checkpoliy.service[
                                                            'protocol'] == j.service[
                                                                'protocol']:
                                                # print("-------------------------匹配-------------------------------------")
                                                # checkpoliy.printpolicymic()
                                                # j.printpolicymic()
                                                iscontent = 2
                                                break
                            # 标识  表示 1= 相关安全域策略未匹配 2= 匹配(存在相对应的策略)
                            if iscontent == 1:
                                temppolicydic = {
                                    'dev': routelist[i].name,
                                    'id': checkpoliy.policyid,
                                    'srceth': checkpoliy.srceth,
                                    'dsteth': checkpoliy.dsteth,
                                    'srcaddr': checkpoliy.srcaddr,
                                    'dstaddr': checkpoliy.dstaddr,
                                    'protocol': checkpoliy.service['protocol'],
                                    'port': checkpoliy.service['port']
                                }
                                zmbiepolicylist.append(temppolicydic)
    return zmbiepolicylist
Ejemplo n.º 8
0
def searchpolicy(srcaddr, dstaddr, protocol, service):
    searchpolicydic = {}
    dstnet = ""
    srcnet = ""
    # 解析IP地址在拓扑中对应的节点,如果节点未在拓扑中添加则退出不进行查找
    if dstaddr == "0.0.0.0" or dstaddr == "0.0.0.0/0":
        dstnet = Topo.internet
    else:
        for i in Topo.netaddrlist:
            if i != Topo.internet:
                if 1 == IPy.IP(i.netaddr).overlaps(dstaddr) or 1 == IPy.IP(
                        dstaddr).overlaps(i.netaddr):
                    dstnet = i
                    break
            elif IPy.IP(dstaddr).iptype() == 'PUBLIC':
                dstnet = Topo.internet
    if srcaddr == "0.0.0.0" or srcaddr == "0.0.0.0/0":
        srcnet = Topo.internet
    else:
        for i in Topo.netaddrlist:
            if i != Topo.internet:
                if 1 == IPy.IP(i.netaddr).overlaps(srcaddr) or 1 == IPy.IP(
                        srcaddr).overlaps(i.netaddr):
                    srcnet = i
                    break
            elif IPy.IP(srcaddr).iptype() == 'PUBLIC':
                srcnet = Topo.internet

    # 根据策略的源区域和目的区域 确认策略路径 生成路径设备列表
    if not srcnet or not dstnet:
        return False, False
    else:
        try:
            routelist = networkx.shortest_path(Topo.nxtopology,
                                               source=srcnet,
                                               target=dstnet)
        except:
            logger.info(srcnet.name + " to " + dstnet.name + "路径不完整")
    # 遍历路径设备列表
    for i in range(len(routelist)):
        searchpolicylist = []
        if routelist[i].type == 'firewall':
            # 根据上下游设备 确定检测策略经过本机的安全域或端口
            srceth = ''
            dsteth = ''
            firewall_zone = Firewall_Policy_Zone.objects.filter(
                Network_Assets_id=routelist[i].assetid)
            for port in firewall_zone:
                if routelist[i - 1].name in port.assets_name:
                    srceth = port.zone
                if routelist[i + 1].name in port.assets_name:
                    dsteth = port.zone
            logger.info("srceth:" + srceth + "  " + "dsteth:" + dsteth)
            # 遍历主机原子策略表,与经过的安全域策略比较是否有相应的策略
            for j in routelist[i].policymiclist:
                if j.srceth == srceth and j.dsteth == dsteth:
                    if IPy.IP(srcaddr).overlaps(j.srcaddr) == 1 or IPy.IP(
                            j.srcaddr).overlaps(srcaddr) == 1:
                        if IPy.IP(dstaddr).overlaps(j.dstaddr) == 1 or IPy.IP(
                                j.dstaddr).overlaps(dstaddr) == 1:
                            if protocol == '0' or j.service['protocol'] == '0':
                                # print("--------------------------------------------------------------")
                                # checkpoliy.printpolicymic()
                                searchpolicylist.append(j)
                            elif protocol == j.service[
                                    'protocol'] and service == j.service[
                                        'port']:
                                # print("--------------------------------------------------------------")
                                # checkpoliy.printpolicymic()
                                searchpolicylist.append(j)
        searchpolicydic.update({routelist[i].name: searchpolicylist})
    return routelist, searchpolicydic
Ejemplo n.º 9
0
 def del_ssh_connect(self):
     self.client.close()
     logger.info("%s SSH 连接关闭", self.hostname)
Ejemplo n.º 10
0
	def parseconffile(self,conf_cwd):
		logger.info("开始解析F1030配置文件")
		ls = os.getcwd()
		f = open(conf_cwd, 'r', encoding="GBK")
		key = ''
		for line in f:
			if not line[0].isspace():
				tokks = re.split(''' (?=(?:[^'"]|'[^']*'|"[^"]*")*$)''', line.strip())
				if 'object' in line:
					if tokks[0] == 'object-group':
						key = tokks[1]
						if tokks[1] == 'ip':
							tempaddr = Addr(tokks[3])
							self.addrlist.append(tempaddr)
						elif tokks[1] == 'service':
							tempser = Ser(tokks[2])
							self.serlist.append(tempser)
					elif tokks[0] == 'object-policy':
						key = tokks[0].split('-')[1] + ':' + tokks[2]
				elif tokks[0] == 'security-zone':
					self.zone.append(tokks[2])
				else:
					key = ''
			elif key:
				if key == 'ip':
					tokks = line.strip().split(' ')
					if tokks[0].isdigit():
						if tokks[2] == 'host':
							self.addrlist[len(self.addrlist) - 1].addrcontent.append(tokks[4])
						elif tokks[2] == 'subnet':
							ipaddr = tokks[3] + '/' + tokks[4]
							self.addrlist[len(self.addrlist) - 1].addrcontent.append(str(IPy.IP(ipaddr, make_net=True)))
				elif key == 'service':
					tokks = re.split(''' (?=(?:[^'"]|'[^']*'|"[^"]*")*$)''', line.strip())
					if tokks[0].isdigit():
						servicedic = {}
						if tokks[2] == 'tcp':
							if tokks[3] == 'destination':
								servicedic = {'protocol': '6', 'port': tokks[5]}
							else:
								continue
						elif tokks[2] == 'udp':
							if tokks[3] == 'destination':
								servicedic = {'protocol': '17', 'port': tokks[5]}
							else:
								continue
						elif tokks[2] == 'icmp':
							servicedic = {'protocol': '1', 'port': '-1'}
						elif tokks[2] == 'group-object':
							servicedic = {'protocol': '-1', 'port': '-1'}

						self.serlist[len(self.serlist) - 1].sercontent.append(servicedic)
				elif 'policy' in key:
					tokks = re.split(''' (?=(?:[^'"]|'[^']*'|"[^"]*")*$)''', line.strip())
					policydic = {}
					if tokks[2] == 'pass':
						self.policylist.append(Policy(key.split(':')[1] + tokks[1]))
						self.policylist[len(self.policylist) - 1].srceth = key.split(':')[1].split('-')[0]
						self.policylist[len(self.policylist) - 1].dsteth = key.split(':')[1].split('-')[1]
						for i in range(3, len(tokks), 2):
							if tokks[i] == 'counting' or tokks[i] == 'logging':
								continue
							policydic[tokks[i]] = tokks[i + 1]
						if 'source-ip' in policydic.keys():
							self.policylist[len(self.policylist) - 1].srcaddr.append(policydic['source-ip'])
						else:
							self.policylist[len(self.policylist) - 1].srcaddr.append('any')
						if 'destination-ip' in policydic.keys():
							self.policylist[len(self.policylist) - 1].dstaddr.append(policydic['destination-ip'])
						else:
							self.policylist[len(self.policylist) - 1].dstaddr.append('any')
						if 'service' in policydic.keys():
							self.policylist[len(self.policylist) - 1].service.append(policydic['service'])
						else:
							self.policylist[len(self.policylist) - 1].service.append('any')
		f.close()