工作记录:项目json格式配置文件解析

项目json格式配置文件解析

declareTree.py

# -*- coding: utf-8 -*-

import os
import sys
import string
import random

g_id = [1]
def create_diff_node_id():
    g_id[0] = g_id[0] + 1
    return g_id[0]

class declareTree:

    def __init__(self):
        self.nodeList=[]

    @staticmethod
    def parse(file_name):
        """ transform the file into declareTree object

        [Paramas]
        - 'file_name' : the name of the file to transform

        [Return]
        - 'tree' : the tree after transform
        """

        file = open(file_name,'rb')
        tree = declareTree()
        child=None
        temp=None
        for line in file:
            if line.strip().find("declare") >= 0:
                temp = child
                child = declareNode(line.strip())
                if child != None and temp != None:
                    temp.add_node(child)
                    child = child.parent
                if child.parent == None:
                    tree.nodeList.append(child)
            elif line.strip().find("{}") > 0:
                temp=child
                child = declareNode(line.strip())
                temp.add_node(child)
                child = child.parent
            elif line.strip().find("[]") > 0:
                temp=child
                child = declareNode(line.strip())
                temp.add_node(child)
                child = child.parent
            elif line.strip().find("{") == 0:
                temp=child
                child = declareNode("{")
                if child != None and temp != None:
                    temp.add_node(child)
            elif line.strip().find("{") > 0:
                temp=child
                child = declareNode(line.strip())
                temp.add_node(child)
            elif line.strip().find("}") >= 0:
                child.namelist[1] = line.strip()
                if child.parent == None:
                    tree.nodeList.append(child)
                child = child.parent
            elif line.strip().find("[") > 0:
                temp=child
                child = declareNode(line.strip())
                temp.add_node(child)
            elif line.strip().find("]") >= 0:
                child.namelist[1] = line.strip()
                if child.parent == None:
                    tree.nodeList.append(child)
                child = child.parent
            elif line.strip() == '':
                continue
            else:
                child.conf.append(line.strip())

        file.close()
        return tree


    def write(self,file_name):

        file = open(file_name,'w')
        for node in self.nodeList:
            node.write(file)
        file.close()
        

class declareNode:
    """
        The base unit of the configure. It starts with "declare",end with "}"

        [Example]
        declare NAME
        {
            CONF

            other declareNodes
        }
    """

    def __init__(self,name1,name2=''):
        self.child_node=[]
        self.namelist=[name1,name2]
        self.conf=[]
        self.parent=None
        self.level=0
        self.id=0

    def deepfind_name(self,name):
        temp = None
        if self.namelist[0].find(name) >= 0:
            return self
        else:
            for node in self.child_node:
                temp = node.deepfind_name(name)
                if temp != None:
                    return temp
            return temp

    def deepfind_conf(self,name):
        temp = None
        for index in range(len(self.conf)):
            if self.conf[index].find(name) >= 0:
                return self,index
        for node in self.child_node:
            temp,num = node.deepfind_conf(name)
            if temp != None:
                return temp,num
        return temp,None

    def add_node(self,node):
        """ add a subnode to the end of this node
        [paramas]
        - 'node' : the subnode to add
        [Return]
        - 'None'
        """
        self.child_node.append(node)
        node.parent = self
        node.level = self.level+1       
    def write(self,file):
        """ write the node to the file
        [Paramas]
        - 'file' : the file object
        [Return]
        - 'None'
        """
        leveltext="\t"*self.level
        file.write("%s%s\n"%(leveltext,self.namelist[0]))
        #dict1 = sorted(self.conf.iteritems(),key = lambda asd:asd[0])
        for item in self.conf:
            file.write("%s\t%s\n"%(leveltext,item))
        for node in self.child_node:
            node.write(file)
        file.write("%s%s\n"%(leveltext,self.namelist[1]))



if __name__ == '__main__':
    obj = declareTree()
View Code

VPNAccess.py

# -*- coding: utf-8 -*-

import os
import sys
import string
import shutil
from declareTree import *
from VPN_Global_Variables_Common import *

work_path = os.path.dirname(__file__)


class VPNAccess:

    def create_tmp_conf(self, tmp_conf_name):
        """ 拷贝python工作目录下的conf目录的基础配置文件到conf/tmp目录,
        [Paramas]
        - '原配置文件名称'

        [Return]
        - '临时配置文件完整目录'
        """
        base_conf_path = "%s/conf/%s" % (work_path, g_service_baseconf_name)
        tmp_conf_path = "%s/conf/tmp/%s" % (work_path, tmp_conf_name)
        shutil.copyfile(base_conf_path, tmp_conf_path)
        VPNAccess.global_conf_setting(self, tmp_conf_path, 'name', tmp_conf_name[4:-5])
        return tmp_conf_path

    def add_site2site_accesspolicy(self, conf_path, srcVlanId, dstVlanId, srcIpAddress, DestIpAddress):
        """ 添加site2site互访策略到文件

        [Paramas]
        - 'conf_path': 添加应用的文件
        - 'srcVlanId': 源vlan ID
        - 'dstVlanId': 目的vlan ID
        - 'srcIpAddress‘:源IP和掩码,如1.2.3.0/24
        - 'DestIpAddress‘:目的IP和掩码,如1.2.3.4/32
        [Return]
        - 'NONE'
        """
        tree = declareTree.parse(conf_path)
        site2siteAccessPolicyNode = tree.nodeList[0].deepfind_name("\"access_policy\"")
        if site2siteAccessPolicyNode == None:
            raise AssertionError("Find Site2siteAccessPolicy Failed!")
        if len(site2siteAccessPolicyNode.child_node) == 0:
            node = declareNode("{", "}")
        else:
            node = declareNode(",{", "}")
        node.conf.append("\"svlan\": %s," % srcVlanId)
        node.conf.append("\"dvlan\": %s," % dstVlanId)
        node.conf.append("\"src\": \"%s\"," % srcIpAddress)
        node.conf.append("\"dst\": \"%s\"" % DestIpAddress)
        site2siteAccessPolicyNode.add_node(node)
        tree.write(conf_path)

    def remove_site2site_accesspolicy(self, conf_path):
        """ 删除site2site所有互访策略
        [Paramas]
        - 'conf_path':删除site2site互访策略配置的文件
        
        [Return]
        - 'NONE'
        """
        tree = declareTree.parse(conf_path)
        Site2siteAccessPolicyNode = tree.nodeList[0].deepfind_name("\"access_policy\"")
        if Site2siteAccessPolicyNode == None:
            raise AssertionError("Find Site2siteAccessPolicy Failed!")
        if len(Site2siteAccessPolicyNode.child_node) > 0:
            Site2siteAccessPolicyNode.child_node = []
        else:
            return
        tree.write(conf_path)

    def add_agent(self, conf_path, serial_id, vlan_id):
        """单独添加网点agent信息,适用于主备agent第二个agent信息的添加
        [Paramas]
        - 'conf_path': 操作的文件
        - 'serial_id':网点对应的agent序列号
        - 'vlan_id':   网点id

        [Return]: NULL
        """
        tree = declareTree.parse(conf_path)
        AgentsNode = tree.nodeList[0].deepfind_name("\"agents\"")
        if AgentsNode == None:
            raise AssertionError("Find Agents Failed!")
        if len(AgentsNode.child_node) == 0:
            node = declareNode("{", "}")
        else:
            for agentnode in AgentsNode.child_node:
                if agentnode.conf[0].split('"')[3] == serial_id:
                    return
            node = declareNode(",{", "}")
        node.conf.append("\"name\":\"%s\"," % serial_id)
        node.conf.append("\"vlanid\":%s" % vlan_id)
        AgentsNode.add_node(node)
        tree.write(conf_path)

    def add_vlan(self, conf_path, serial_id, mode, ip, name, pick_path_type=1, connect_num=4,
                 sni_passwd='wscloudvpn@appa', direct_conn_ip='null', direct_conn_port=2668, ac_pop_probe_ratio=100, ac_as_probe_ratio=100 ):
        """ 添加网点及agent信息,默认不使用appa,不开启直连

        [Paramas]
        - 'conf_path': 操作的文件
        - 'serial_id':网点对应的agent序列号
        - 'mode':网点运行模式,server或client
        - 'ip':网点ip
        - 'name':server模式--对应pop接入域名;client模式--对应AS的网点标识
        - 'pick_path_type': 0表示自动化选路,1表示固定路径
        - 'connect_num':tcp连接数量
        - 'sni_passwd':sni传输的加解密密码
        - 'direct_conn_ip':直连ip
        - 'direct_conn_port':直连端口

        [Return]
        - server模式返回vlan_id和网点标识(这里为主机ip),client模式返回vlan_id
        """
        vlan_id = ip.split('.')[3]
        # print conf_path.split('\\')[-1][4:-5]
        channel_name = "ch%s.%s" % (vlan_id, conf_path.split('/')[-1][4:-5])
        channel_name_alias = "%s.%s" % (vlan_id, conf_path.split('/')[-1][4:-5])
        tree = declareTree.parse(conf_path)
        VlancfgsNode = tree.nodeList[0].deepfind_name("\"vlancfgs\"")
        if VlancfgsNode == None:
            raise AssertionError("Find Vlancfgs Failed!")
        if mode == 'server':
            if len(VlancfgsNode.child_node) == 0:
                node1 = declareNode("{", "}")
            else:
                for node in VlancfgsNode.child_node:
                    if node.conf[0].split(':')[1].strip().split(',')[0] == vlan_id:
                        node.child_node[0].conf.append("\"direct_conn_ip\": \"%s\"," % direct_conn_ip)
                        node.child_node[0].conf.append("\"direct_conn_port\": %s," % direct_conn_port)
                        node.child_node[0].conf.append("\"hostname\": \"%s\"," % name)
                        node.child_node[0].conf.append("\"channel_name\": \"%s\"," % channel_name)
                        node.child_node[0].conf.append("\"channel_name_alias\": \"%s\"," % channel_name_alias)
                        node.child_node[0].conf.append("\"pre_conn_num\": %s," % connect_num)
                        node.child_node[0].conf.append("\"port\": 34745")
                        tree.write(conf_path)
                        return vlan_id, channel_name
                node1 = declareNode(",{", "}")
            node1.conf.append("\"vlanid\": %s," % vlan_id)
            node1.conf.append("\"ip\": \"169.254.1.%s\"," % (ip.split('.')[3]))
            node1.conf.append("\"mask\": \"255.255.0.0\",")
            VlancfgsNode.add_node(node1)
            node2 = declareNode("\"server_mode\": {", "},")
            node2.conf.append("\"direct_conn_ip\": \"%s\"," % direct_conn_ip)
            node2.conf.append("\"direct_conn_port\":  %s," % direct_conn_port)
            node2.conf.append("\"hostname\": \"%s\"," % name)
            node2.conf.append("\"channel_name\": \"%s\"," % channel_name)
            node2.conf.append("\"channel_name_alias\": \"%s\"," % channel_name_alias)
            node2.conf.append("\"pre_conn_num\": %s," % connect_num)
            node2.conf.append("\"port\": 34745")
            node3 = declareNode("\"client_mode\": [", "]")
            node1.add_node(node2)
            node1.add_node(node3)
        elif mode == 'client':
            if len(VlancfgsNode.child_node) == 0:
                node1 = declareNode("{", "}")
            else:
                for node in VlancfgsNode.child_node:
                    # print node.conf[0],vlan_id
                    if node.conf[0].split(':')[1].strip().split(',')[0] == vlan_id:
                        if len(node.child_node[1].child_node) == 0:
                            node4 = declareNode("{", "}")
                        else:
                            node4 = declareNode(",{", "}")
                        node4.conf.append("\"dst_channel_name\": \"%s\"," % name)
                        node4.conf.append("\"direct_conn_ip\": \"%s\"," % direct_conn_ip)
                        node4.conf.append("\"direct_conn_port\": %s," % direct_conn_port)
                        node4.conf.append("\"max_connection\": %s," % connect_num)
                        node4.conf.append("\"port\": 34746,")
                        node4.conf.append("\"appa_host\": \"\",")
                        node4.conf.append("\"appa_port\": 34749,")
                        node4.conf.append("\"ac_poplist\": \"\",")
                        node4.conf.append("\"appa_pop_probe_interval\": 10,")
                        node4.conf.append("\"ac_pop_probe_interval\": 10,")
                        node4.conf.append("\"pick_best_path_interval\": 10,")
                        node4.conf.append("\"refresh_interval\": 1000,")
                        node4.conf.append("\"pick_path_type\": %s," % pick_path_type)
                        node4.conf.append("\"ac_pop_probe_ratio\": %s," % ac_pop_probe_ratio)
                        node4.conf.append("\"ac_as_probe_ratio\": %s," % ac_as_probe_ratio)
                        node4.conf.append("\"sni_passwd\":\"%s\"" % sni_passwd)
                        node.child_node[1].add_node(node4)
                        tree.write(conf_path)
                        return vlan_id
                node1 = declareNode(",{", "}")
            node1.conf.append("\"vlanid\": %s," % vlan_id)
            node1.conf.append("\"ip\": \"169.254.1.%s\"," % (ip.split('.')[3]))
            node1.conf.append("\"mask\": \"255.255.0.0\",")
            VlancfgsNode.add_node(node1)
            node2 = declareNode("\"server_mode\": {", "},")
            node3 = declareNode("\"client_mode\": [", "]")
            node1.add_node(node2)
            node1.add_node(node3)
            node4 = declareNode("{", "}")
            node4.conf.append("\"dst_channel_name\": \"%s\"," % name)
            node4.conf.append("\"direct_conn_ip\":\"%s\"," % direct_conn_ip)
            node4.conf.append("\"direct_conn_port\": %s," % direct_conn_port)
            node4.conf.append("\"max_connection\": %s," % connect_num)
            node4.conf.append("\"port\": 34746,")
            node4.conf.append("\"appa_host\": \"\",")
            node4.conf.append("\"appa_port\": 34749,")
            node4.conf.append("\"ac_poplist\": \"\",")
            node4.conf.append("\"appa_pop_probe_interval\": 10,")
            node4.conf.append("\"ac_pop_probe_interval\": 10,")
            node4.conf.append("\"pick_best_path_interval\": 10,")
            node4.conf.append("\"refresh_interval\": 1000,")
            node4.conf.append("\"pick_path_type\": %s," % pick_path_type)
            node4.conf.append("\"ac_pop_probe_ratio\": %s," % ac_pop_probe_ratio)
            node4.conf.append("\"ac_as_probe_ratio\": %s," % ac_as_probe_ratio)
            node4.conf.append("\"sni_passwd\": \"%s\"" % sni_passwd)
            node3.add_node(node4)
        AgentsNode = tree.nodeList[0].deepfind_name("\"agents\"")
        if AgentsNode == None:
            raise AssertionError("Find Agents Failed!")
        if len(AgentsNode.child_node) == 0:
            node = declareNode("{", "}")
        else:
            for agentnode in AgentsNode.child_node:
                if agentnode.conf[0].split('"')[3] == serial_id:
                    if mode == 'server':
                        return vlan_id, channel_name
                    else:
                        return vlan_id
            node = declareNode(",{", "}")
        node.conf.append("\"name\": \"%s\"," % serial_id)
        node.conf.append("\"vlanid\": %s" % vlan_id)
        AgentsNode.add_node(node)
        tree.write(conf_path)
        if mode == 'server':
            return vlan_id, channel_name
        else:
            return vlan_id

    def remove_vlan(self, conf_path):
        """ 删除所有网点及agent信息

        [Paramas]
        - 'conf_path': 操作的文件
        
        [Return]
        - 'NONE'
        """
        tree = declareTree.parse(conf_path)
        VlancfgsNode = tree.nodeList[0].deepfind_name("\"vlancfgs\"")
        if VlancfgsNode == None:
            raise AssertionError("Find Vlancfgs Failed!")
        if len(VlancfgsNode.child_node) > 0:
            VlancfgsNode.child_node = []
        AgentsNode = tree.nodeList[0].deepfind_name("\"agents\"")
        if AgentsNode == None:
            raise AssertionError("Find Agents Failed!")
        if len(AgentsNode.child_node) > 0:
            AgentsNode.child_node = []
        tree.write(conf_path)

    def global_conf_setting(self, conf_path, name, value):
        """ 修改网点配置信息,支持修改
            全局配置 name,conn_mode,as_probe_appa_sni_interval

                [Paramas]
                - 'conf_path': 操作的文件
                - 'name': 要修改的字段名
                - 'value': 要修改的字段对应值

                [Return]
                - 'NONE'
        """
        tree = declareTree.parse(conf_path)
        # 全局配置修改
        if name in ['name']:
            for i in range(len(tree.nodeList[0].conf)):
                if tree.nodeList[0].conf[i].find(name) >= 0:
                    tree.nodeList[0].conf[i] = "\"%s\": \"%s\"," % (name, value)
        elif name in ['conn_mode','ac_appa_probe_interval','as_pop_probe_interval','ac_as_probe_interval']:
            for i in range(len(tree.nodeList[0].conf)):
                if tree.nodeList[0].conf[i].find(name) >= 0:
                    tree.nodeList[0].conf[i] = "\"%s\": %s," % (name, value)
        tree.write(conf_path)

    def vlan_session_setting(self, conf_path, vlan_id, name, value, channel_name=''):
        """ 修改网点配置信息,支持修改
            server mode的hostname,
            client mode的ac_poplist,appa_host,pick_path_type,refresh_interval,ac_pop_probe_ratio字段
            server/client mode的direct_conn_ip,direct_conn_port

                [Paramas]
                - 'conf_path': 操作的文件
                - 'vlan_id': 网点id,add_vlan函数返回值
                - 'name': 要修改的字段名
                - 'value': 要修改的字段对应值
                - 'channel_name': server模式--置空;
                                  client模式--对应AS的网点标识;

                [Return]
                - 'NONE'
        """
        tree = declareTree.parse(conf_path)
        # 网点信息修改
        VlancfgsNode = tree.nodeList[0].deepfind_name("\"vlancfgs\"")
        if VlancfgsNode == None:
            raise AssertionError("Find Vlancfgs Failed!")
        for vlancfg_childnode in VlancfgsNode.child_node:
            # 匹配vlan_id
            if int(vlancfg_childnode.conf[0].split(':')[1].strip().split(',')[0]) == int(vlan_id):
                # server mode字段修改
                if name == 'hostname':
                    for index in range(len(vlancfg_childnode.child_node[0].conf)):
                        if vlancfg_childnode.child_node[0].conf[index].find(name) >= 0:
                            vlancfg_childnode.child_node[0].conf[index] = "\"%s\": \"%s\"," % (name, value)
                # 修改direct_conn_ip或者direct_conn_port时,需要判断是server还是client mode
                elif name in ['direct_conn_ip', 'direct_conn_port']:
                    if channel_name == '':
                        for index in range(len(vlancfg_childnode.child_node[0].conf)):
                            if vlancfg_childnode.child_node[0].conf[index].find(name) >= 0:
                                vlancfg_childnode.child_node[0].conf[index] = "\"%s\": \"%s\"," % (name, value)
                    else:
                        for clientmode_childnode in vlancfg_childnode.child_node[1].child_node:
                            for tmp in clientmode_childnode.conf:
                                if tmp.find(channel_name) >= 0:
                                    for index in range(len(clientmode_childnode.conf)):
                                        if clientmode_childnode.conf[index].find(name) >= 0:
                                            clientmode_childnode.conf[index] = "\"%s\": \"%s\"," % (name, value)
                # client mode字段修改
                else:
                    for clientmode_childnode in vlancfg_childnode.child_node[1].child_node:
                        for tmp in clientmode_childnode.conf:
                            if tmp.find(channel_name) >= 0:
                                for index in range(len(clientmode_childnode.conf)):
                                    if name in ['ac_poplist', 'appa_host']:
                                        if clientmode_childnode.conf[index].find(name) >= 0:
                                            clientmode_childnode.conf[index] = "\"%s\": \"%s\"," % (name, value)
                                    elif name in ['pick_path_type', 'refresh_interval', 'ac_pop_probe_ratio','ac_as_probe_ratio']:
                                        if clientmode_childnode.conf[index].find(name) >= 0:
                                            clientmode_childnode.conf[index] = "\"%s\": %s," % (name, value)
                            else:
                                continue

        tree.write(conf_path)


if __name__ == '__main__':
    obj = VPNAccess()

    # obj.create_tmp_conf(g_service_config2_name)
    # obj.global_conf_setting('E:\\AutoTest\\CloudVPN\\vpnpop\\trunk\\lib\\conf\\tmp\\hub_vpnautotest1.wscloudvpn.com.conf',
    #                         'as_pop_probe_interval',10)
    # obj.vlan_session_setting('E:\\AutoTest\\CloudVPN\\vpnpop\\trunk\\lib\\conf\\tmp\\hub_vpnautotest1.wscloudvpn.com.conf'
    # , 4,'direct_conn_ip', '23.3.4','test')
    # obj.global_conf_setting('E:\\AutoTest\\CloudVPN\\vpnpop\\trunk\\lib\\conf\\tmp\\hub_vpnautotest1.wscloudvpn1.com.conf'
    # ,'conn_mode', '2')
    # obj.vlan_session_setting('E:\\AutoTest\\CloudVPN\\vpnpop\\trunk\\lib\\conf\\tmp\\hub_vpnautotest1.wscloudvpn.com.conf'
    #                        , 4,'pick_path_type', '1.2.3.5,2.2.2.2','test')
    # obj.vlan_session_setting('E:\\AutoTest\\CloudVPN\\vpnpop\\trunk\\lib\\conf\\tmp\\hub_vpnautotest1.wscloudvpn.com.conf'
    #                         , 4,'conn_mode', 1)
    # obj.vlan_session_setting('E:\\AutoTest\\CloudVPN\\vpnpop\\lib\\conf\\tmp\\hub_vpnautotest1.wscloudvpn.com.conf'
    # , 38,'refresh_interval', '22','ch33.pop.com')
    # obj.add_vlan('E:\\AutoTest\\CloudVPN\\vpnpop\\trunk\\lib\\conf\\tmp\\hub_vpnautotest1.wscloudvpn.conf','ssss','client',
    #            '1.2.3.4','test')
    # obj.add_vlan('E:\\AutoTest\\CloudVPN\\vpnpop\\trunk\\lib\\conf\\tmp\\hub_vpnautotest1.wscloudvpn.com.conf', 'ssss',
    #              'server','1.2.3.4', 'pop.com')
View Code

操作配置文件库文件

VPNC2S.py

# -*- coding: utf-8 -*-

import os
import sys
import string
import shutil
from declareTree import *
from VPNAccess import VPNAccess

work_path = os.path.dirname(__file__)


class VPNC2S:

    def edit_client_config(self,conf_path,uname,passwd,channelname,authtype=1):
        """
        修改客户端登录相关参数
        :param conf_path: 客户端配置文件路径
        :param uname: 用户名
        :param passwd: 加密后的密码
        :param channelname: pop接入域名
        :param authtype: 认证方式,1=本地认证
        :return: NULL
        """
        tree = declareTree.parse(conf_path)
        #修改用户名
        clientconfig_node,index = tree.nodeList[0].deepfind_conf("Username")
        if clientconfig_node == None:
            raise AssertionError("Find clientconfig_node Failed!")
        clientconfig_node.conf[index] = "string Username %s" %uname
        #修改密码,加密
        clientconfig_node,index = tree.nodeList[0].deepfind_conf("HashedPassword")
        if clientconfig_node == None:
            raise AssertionError("Find clientconfig_node Failed!")
        clientconfig_node.conf[index] = "byte HashedPassword %s" %passwd
        #修改pop接入域名
        clientconfig_node, index = tree.nodeList[0].deepfind_conf("Hostname")
        if clientconfig_node == None:
            raise AssertionError("Find clientconfig_node Failed!")
        clientconfig_node.conf[index] = "string Hostname %s" %channelname
        #修改认证方式
        clientconfig_node, index = tree.nodeList[0].deepfind_conf("AuthType")
        if clientconfig_node == None:
            raise AssertionError("Find clientconfig_node Failed!")
        clientconfig_node.conf[index] = "uint AuthType %s" %authtype
        tree.write(conf_path)

    def add_application(self,conf_path,mode,value,app_id='null'):
        """
        增加应用
        :param conf_path: vcs配置文件路径
        :param mode: network==ip网段,需要有掩码,如1.2.3.4/32,domain==域名
        :param value: 网段或者域名
        :param app_id:生成指定app_id的应用,默认系统自己生成
        :return: app_id
        """
        tree = declareTree.parse(conf_path)
        applicationyNode = tree.nodeList[0].deepfind_name("application")
        if applicationyNode == None:
            raise AssertionError("Find applicationy Failed!")
        if len(applicationyNode.child_node) == 0:
            node = declareNode("{", "}")
        else:
            node = declareNode(",{", "}")
        applicationyNode.add_node(node)
        if app_id == 'null':
            app_id = create_diff_node_id()
        node.conf.append("\"id\": %s," % app_id)
        node1 = declareNode("\"proto\": [", "],")
        node1.conf.append("\"all\"")
        node2 = declareNode("\"ports\": [", "],")
        node2.conf.append("\"0-65535\"")
        if mode == 'network':
            node3 = declareNode("\"network\": [", "],")
            node3.conf.append("\"%s\""%value)
            node4 = declareNode("\"domain\": [", "]")
        elif mode == 'domain':
            node3 = declareNode("\"network\": [", "],")
            node4 = declareNode("\"domain\": [", "]")
            node4.conf.append("\"%s\"" % value)
        node.add_node(node1)
        node.add_node(node2)
        node.add_node(node3)
        node.add_node(node4)
        tree.write(conf_path)
        return app_id

    def del_application(self, conf_path):
        """ 删除所有应用信息
        [Paramas]
        - 'conf_path': 操作的文件
        [Return]
        - 'NONE'
        """
        tree = declareTree.parse(conf_path)
        applicationyNode = tree.nodeList[0].deepfind_name("application")
        if applicationyNode == None:
            raise AssertionError("Find applicationy Failed!")
        if len(applicationyNode.child_node) > 0:
            applicationyNode.child_node = []
        tree.write(conf_path)

    def add_group(self,conf_path,app_id,group_id='null',group_name='null'):
        """
        增加权限组,及其包含的权限
        :param conf_path: vcs配置文件路径
        :param app_id: 包含的应用id,多个用逗号分隔,如2,3,5
        :param group_id:生成指定group_id的权限组,默认系统自己生成
        :param group_name:权限组名称,默认空,ldap权限组使用
        :return: group_id
        """
        tree = declareTree.parse(conf_path)
        groupnode = tree.nodeList[0].deepfind_name("\"group\"")
        if groupnode == None:
            raise AssertionError("Find group Failed!")
        if len(groupnode.child_node) == 0:
            node = declareNode("{", "}")
        else:
            node = declareNode(",{", "}")
        groupnode.add_node(node)
        if group_id == 'null':
            group_id = create_diff_node_id()
            node.conf.append("\"id\": \"%s\"," % group_id)
        else:
            node.conf.append("\"id\": \"%s\"," % group_id)
        if group_name == 'null':
            node1 = declareNode("\"name\": {", "},")
            node.add_node(node1)
        else:
            node.conf.append("\"name\": \"%s\"," % group_name)
        node2 = declareNode("\"appid\": [", "]")
        node2.conf.append("%s"%app_id)
        node.add_node(node2)
        tree.write(conf_path)
        return group_id

    def edit_group(self,conf_path,group_id,app_id,group_name='null'):
        """
        修改权限组对应的权限
        :param conf_path: vcs配置文件路径
        :param group_id
        :param app_id: 包含的应用id,多个用逗号分隔,如2,3,5
        :param group_name:权限组名称,默认空,ldap权限组使用
        [Return]
        - 'NONE'
        """
        tree = declareTree.parse(conf_path)
        groupnode = tree.nodeList[0].deepfind_name("\"group\"")
        if groupnode == None:
            raise AssertionError("Find group Failed!")
        groupapp_node, num = groupnode.deepfind_conf("\"id\": \"%s\"," % group_id)
        if groupapp_node == None:
            raise AssertionError("Find groupapp_node Failed!")
        if group_name == 'null':
            groupapp_node.child_node[1].conf[0] = "%s"%app_id
        else:
            groupapp_node.child_node = []
            node1 = declareNode("\"name\": {", "},")
            groupapp_node.add_node(node1)
            node2 = declareNode("\"appid\": [", "]")
            node2.conf.append("%s" % app_id)
            groupapp_node.add_node(node2)
        tree.write(conf_path)

    def del_group(self, conf_path):
        """ 删除所有权限组
        [Paramas]
        - 'conf_path': 操作的文件
        [Return]
        - 'NONE'
        """
        tree = declareTree.parse(conf_path)
        groupnode = tree.nodeList[0].deepfind_name("\"group\"")
        if groupnode == None:
            raise AssertionError("Find group Failed!")
        if len(groupnode.child_node) > 0:
            groupnode.child_node = []
        tree.write(conf_path)

    def add_user(self,conf_path,uname,passwd,group_id):
        """
        增加用户,及其包含的权限组
        :param conf_path: vcs配置文件路径
        :param uname:用户名
        :param passwd:加密后的密码
        :param group_id: 包含的权限组id,多个用逗号分隔,如2,3,5
        :return: NULL
        """
        tree = declareTree.parse(conf_path)
        usernode = tree.nodeList[0].deepfind_name("\"user\"")
        if usernode == None:
            raise AssertionError("Find user Failed!")
        if len(usernode.child_node) == 0:
            node = declareNode("{", "}")
        else:
            node = declareNode(",{", "}")
        usernode.add_node(node)
        node.conf.append("\"name\": \"%s\"," % uname)
        node.conf.append("\"passwd\": \"%s\"," % passwd)
        node1 = declareNode("\"gid\": [", "]")
        node1.conf.append("%s"%group_id)
        node.add_node(node1)
        tree.write(conf_path)

    def del_alluser(self, conf_path):
        """ 删除所有用户
        [Paramas]
        - 'conf_path': 操作的文件
        [Return]
        - 'NONE'
        """
        tree = declareTree.parse(conf_path)
        usernode = tree.nodeList[0].deepfind_name("\"user\"")
        if usernode == None:
            raise AssertionError("Find user Failed!")
        if len(usernode.child_node) > 0:
            usernode.child_node = []
        tree.write(conf_path)

    def del_user(self, conf_path,uname):
        """ 删除指定用户
        [Paramas]
        - 'conf_path': 操作的文件
        - 'uname' :用户名
        [Return]
        - 'NONE'
        """
        tree = declareTree.parse(conf_path)
        usernode = tree.nodeList[0].deepfind_name("\"user\"")
        if usernode == None:
            raise AssertionError("Find user Failed!")
        unamenode,num = usernode.deepfind_conf("\"%s\""%uname)
        print "%s"%unamenode.conf
        usernode.child_node.remove(unamenode)
        if len(usernode.child_node) > 0:
            usernode.child_node[0].namelist[0] = "{"
        tree.write(conf_path)

    def edit_clientconn_info(self,conf_path,appa_host='sni.wscloudvpn.com',appa_port=34749,pop_port=34746,sni_passwd='wscloudvpn@appa',use_probe='false',
                             client_pop_probe_ratio=100,client_as_probe_ratio=100,as_triger_ssl_probe_interval=300,client_probe_interval=10,
                             client_probe_interval_max=20,client_route_rtt_threshold=50,refresh_interval=30,c2s_use_appa='false'):
        """
        修改客户端连接信息,默认不使用appa
        :param conf_path:配置文件路径
        :param appa_host: 默认sni.wscloudvpn.com,是否使用appa改用c2s_use_appa控制
        :param appa_port:
        :param pop_port:
        :param sni_passwd:
        :param use_probe:true/false
        :param c2s_use_appa: true使用appa,flase不使用appa
        :return:
        """
        tree = declareTree.parse(conf_path)
        connnode = tree.nodeList[0].deepfind_name("conn_info")
        if connnode == None:
            raise AssertionError("Find user Failed!")
        connnode.conf[0] = "\"appa_host\":\"%s\"," %appa_host
        connnode.conf[1] = "\"appa_port\":%s," % appa_port
        connnode.conf[2] = "\"port\":%s," % pop_port
        connnode.conf[3] = "\"sni_passwd\":\"%s\"," % sni_passwd
        connnode.conf[4] = "\"use_probe\":%s," % use_probe
        connnode.conf[5] = "\"client_pop_probe_ratio\":%s," % client_pop_probe_ratio
        connnode.conf[6] = "\"client_as_probe_ratio\":%s," % client_as_probe_ratio
        connnode.conf[7] = "\"as_triger_ssl_probe_interval\":%s," % as_triger_ssl_probe_interval
        connnode.conf[8] = "\"client_probe_interval\":%s," % client_probe_interval
        connnode.conf[9] = "\"client_probe_interval_max\":%s," % client_probe_interval_max
        connnode.conf[10] = "\"client_route_rtt_threshold\":%s," % client_route_rtt_threshold
        connnode.conf[11] = "\"refresh_interval\":%s," % refresh_interval
        connnode.conf[12] = "\"c2s_use_appa\":%s" % c2s_use_appa
        tree.write(conf_path)

    def edit_dhcp_server(self,conf_path,virtual_host_ip,mask,beginIP,endIP,mainDns='',backDns=''):
        """
        修改dhcp服务器相关参数
        :param conf_path:
        :param virtual_host_ip: 虚拟主机ip,同时也是默认网关
        :param mask: 掩码
        :param beginIP: 起始ip
        :param endIP: 结束ip
        :param mainDns: 主dns服务器
        :param backDns: 备dns服务器
        :return: NULL
        """
        tree = declareTree.parse(conf_path)
        dhcpnode = tree.nodeList[0].deepfind_name("\"dhcp\"")
        if dhcpnode == None:
            tree.nodeList[0].conf.remove('\"dhcp\":null,')
            dhcpnode = declareNode(",\"dhcp\": {", "}")
            tree.nodeList[0].add_node(dhcpnode)
        else:
            dhcpnode.conf = []
        dhcpnode.conf.append("\"mask\":\"%s\"," % mask)
        dhcpnode.conf.append("\"beginIP\":\"%s\"," % beginIP)
        dhcpnode.conf.append("\"endIP\":\"%s\"," % endIP)
        dhcpnode.conf.append("\"mainDns\":\"%s\"," % mainDns)
        dhcpnode.conf.append("\"backDns\":\"%s\"," % backDns)
        dhcpnode.conf.append("\"gateway\":\"%s\"" % virtual_host_ip)
        tree.write(conf_path)

    def del_dhcp_server(self,conf_path):
        tree = declareTree.parse(conf_path)
        dhcpnode = tree.nodeList[0].deepfind_name("\"dhcp\"")
        if dhcpnode == None:
            return
        tree.nodeList[0].child_node.remove(dhcpnode)
        tree.nodeList[0].conf.append("\"dhcp\":null,")
        tree.write(conf_path)

    def edit_ldap_server(self,conf_path,ip,port,dnAdmin,passwd,dnEntry,timeout='15',enableAnonymous='0',userAttribute='sAMAccountName',userFilter='objectClass=person'):
        """
        修改ldap服务器相关配置
        :param conf_path:
        :param ip: 服务器地址
        :param port: 服务器端口号
        :param dnAdmin: 管理员全路径
        :param passwd: 管理员密码
        :param dnEntry: 认证查询路径
        :param timeout: 查询超时时间(秒)
        :param enableAnonymous: 匿名登录,目前不用
        :param userAttribute: 登录名属性
        :param userFilter: 用户过滤参数
        :return: Null
        """
        tree = declareTree.parse(conf_path)
        ldapnode = tree.nodeList[0].deepfind_name("\"ldap\"")
        if ldapnode == None:
            tree.nodeList[0].conf.remove('\"ldap\":null,')
            ldapnode = declareNode(",\"ldap\": {", "}")
            tree.nodeList[0].add_node(ldapnode)
        else:
            ldapnode.conf = []
        ldapnode.conf.append("\"ip\":\"%s\"," % ip)
        ldapnode.conf.append("\"port\":%s," % port)
        ldapnode.conf.append("\"dnAdmin\":\"%s\"," % dnAdmin)
        ldapnode.conf.append("\"passwd\":\"%s\"," % passwd)
        ldapnode.conf.append("\"dnEntry\":\"%s\"," % dnEntry)
        ldapnode.conf.append("\"timeout\":%s," % timeout)
        ldapnode.conf.append("\"enableAnonymous\":\"%s\"," % enableAnonymous)
        ldapnode.conf.append("\"userAttribute\":\"%s\"," % userAttribute)
        ldapnode.conf.append("\"userFilter\":\"%s\"" % userFilter)
        tree.write(conf_path)

    def del_ldap_server(self,conf_path):
        tree = declareTree.parse(conf_path)
        ldapnode = tree.nodeList[0].deepfind_name("\"ldap\"")
        if ldapnode == None:
            return
        tree.nodeList[0].child_node.remove(ldapnode)
        tree.nodeList[0].conf.append("\"ldap\":null,")
        tree.write(conf_path)

    def get_vpnclient_ip(self,interface_name="VPN"):
        #获取客户端登录后获取的ip
        #return ip
        interface_id = os.popen("route print inteface|findstr %s" % interface_name).read().strip().split(".")[0]
        vpnclient_ip = os.popen("netsh interface ipv4 show ipaddresses interface=%s" % interface_id).read().strip().split("----")[0].split(" ")[1]
        #print vpnclient_ip
        if "169.254." not in vpnclient_ip:
            return vpnclient_ip
        return None



if __name__ == '__main__':
    obj = VPNC2S()
    #VPNAccess().create_tmp_conf('hub_vpnautotest.baseconf1.com.conf')
    #obj.edit_client_config('E:\\AutoTest\\CloudVPN\\vpnpop\\lib\\conf\\tmp\\vpn_client.config','test','test','test',2)
    #obj.add_application('E:\\AutoTest\\CloudVPN\\vpnpop\\lib\\conf\\tmp\\hub_vpnautotest.baseconf1.com.conf', 'domain', 'test',34)
    #print obj.add_application('E:\\AutoTest\\CloudVPN\\vpnpop\\lib\\conf\\tmp\\hub_vpnautotest.baseconf1.com.conf', 'network','12.3.4.5/32')
    #print obj.add_user('E:\\AutoTest\\CloudVPN\\vpnpop\\lib\\conf\\tmp\\hub_vpnautotest.baseconf1.com.conf','aaaa','72639%!##','1,2,3')
    #print obj.add_user('E:\\AutoTest\\CloudVPN\\vpnpop\\lib\\conf\\tmp\\hub_vpnautotest.baseconf1.com.conf', 'bbbb','7ss3s#', '1,2,3')
    #print obj.add_user('E:\\AutoTest\\CloudVPN\\vpnpop\\lib\\conf\\tmp\\hub_vpnautotest.baseconf1.com.conf', 'ccd','7ss3s#', '1,2,3')
    #obj.edit_group('E:\\AutoTest\\CloudVPN\\vpnpop\\lib\\conf\\tmp\\hub_vpnautotest.baseconf1.com.conf','286', '12,233,4,2,3')
    #obj.del_application('E:\\AutoTest\\CloudVPN\\vpnpop\\lib\\conf\\tmp\\hub_vpnautotest.baseconf1.com.conf')
    #obj.del_user('E:\\AutoTest\\CloudVPN\\vpnpop\\lib\\conf\\tmp\\hub_vpnautotest.baseconf1.com.conf')
    #obj.del_user('E:\\AutoTest\\CloudVPN\\vpnpop\\lib\\conf\\tmp\\hub_vpnautotest.baseconf1.com.conf','autouser1')
    #obj.edit_dhcp_server('E:\\AutoTest\\CloudVPN\\vpnpop\\lib\\conf\\tmp\\hub_vpnautotest.baseconf1.com.conf','1.2.3.4', '255.0.0.0', '1.2.3.5', '1.2.3.10','','22')
    #obj.del_dhcp_server('E:\\AutoTest\\CloudVPN\\vpnpop\\lib\\conf\\tmp\\hub_vpnautotest.baseconf1.com.conf')
    #obj.edit_ldap_server('E:\\AutoTest\\CloudVPN\\vpnpop\\lib\\conf\\tmp\\hub_vpnautotest.baseconf1.com.conf',
    #                     '1.2.3.4', '333', 'CN=陈金玉,OU=组                  二abc,OU=网研二,DC=VPNcloud,DC=com', '1234', 'DC=VPNcloud,DC=com', enableAnonymous='1')
    #obj.del_ldap_server('E:\\AutoTest\\CloudVPN\\vpnpop\\lib\\conf\\tmp\\hub_vpnautotest.baseconf1.com.conf')
    print obj.get_vpnclient_ip()
View Code

另外win客户端操作库文件

VPNClient.py

# -*- coding: utf-8 -*-
import os,sys,requests,time
from VPN_FileProcess import *
reload(sys)
sys.setdefaultencoding('utf-8')

work_path = os.path.dirname(__file__)


class VPNClient:
    def vpn_client_logout(self):
        print "hi"

    def vpn_client_exit(self):
        print "hi"

    def check_process_ifexist(self, process_name,ifexist="yes"):
        """校验指定进程是否存在
        :param process_name: 进程名称
        :param ifexist: yes/no

        :return: None
        """
        status = os.popen("tasklist|findstr %s" % process_name).read().strip()
        print status
        if ifexist == 'yes':
            if len(status) == 0:
                raise AssertionError("Error! There does not exist %s!" % process_name)
        elif ifexist == 'no':
            if len(status) != 0:
                raise AssertionError("Error! There already exist %s!" % process_name)
        else:
            raise AssertionError("Error! Please input 'yes' or 'no'!")

    def file_ifcontain_keyword(self, filepath, keyword, ifcontain="yes"):
        flag = 0
        with open(filepath, 'r') as fo:
            for line in fo.readlines():
                if keyword in line.strip():
                    print  "The keyword in result_file is:'%s'"% line
                    flag = flag + 1
        if ifcontain =="yes":
            if flag ==0:
                raise AssertionError("Error! There has no '%s' in '%s'" % (keyword,filepath))
        elif ifcontain =="no":
            if flag !=0:
                raise AssertionError("Error! There has '%s' in '%s'" % (keyword,filepath))
        else:
            raise AssertionError("Error! Please input 'yes' or 'no'!")

    def v_file_contain_x_times_keyword(self, filepath, keyword):
        flag = 0
        with open(filepath, 'r') as fo:
            for line in fo.readlines():
                if keyword in line.strip():
                    flag = flag + 1
        print "The '%s' in '%s' exist %s times!" % (keyword, filepath, flag)
        return int(flag)

    def browser_access_url(self,url):
        """返回访问url的页面内容"""
        res_text = requests.get(url).text
        print "Access url:%s, The result is:%s" % (url,res_text)
        return res_text

    def vpn_client_login_http(self,username,password,point,idle="no",disconnect_time=8,login_result=0,max_waittime=8):
        """

        :param username:
        :param password:
        :param point:
        :param idle:
        :param disconnect_time:
        :param max_waittime:
        :return:
        """
        #先进行SetConnect
        self.browser_access_url("http://127.0.0.1:9001/SetConnect?user=%s&passwd=%s&point=%s&idle=%s&time=%s"% (username,password,point,idle,time))
        #TryConnect
        self.browser_access_url("http://127.0.0.1:9001/TryConnect")

        #获取ConnectStatus
        waittime = 0
        while True:
            connect_status = self.browser_access_url("http://127.0.0.1:9001/ConnectStatus")
            if "Established" in connect_status:
                return connect_status
            time.sleep(0.5)
            waittime = waittime + 0.5
            if waittime > max_waittime:
                return connect_status
                break

    def vpn_client_login_ifsuccess_check(self, if_useappa='0', if_loginsuccess='0',if_derect_conn='0'):
        """client登录后,10秒内循环检查客户端是否建立了三条指定链路。主要在【client重启并登录】关键字中使用。

        :param if_useappa: 是否使用了appa,默认0=不使用,1=使用,使用了appa则端口为34749,否则再判断是否直连,直连端口默认2668,非直连2666
        :param if_loginsuccess: 登录方式,0=正常登录,1=异常登录
        :param if_derect_conn: 是否直连,0=非直连,1=直连
        :return: None
        """
        if if_useappa == '0' and if_derect_conn == '0':
            port = g_client2pop_port
        elif if_useappa == '0' and if_derect_conn == '1':
            port = g_direct_conn_port
        elif if_useappa == '1':
            port = g_client2appa_port
        else:
            raise AssertionError("Error! Please input '0' or '1'!")
        wait_time=0
        time_interval=0.5
        max_wait_time = 8
        while True:
            print "[netstat -ano|findstr \":%s :%s :%s\"] result is:\n"%(g_client2pop_port,g_direct_conn_port,g_client2appa_port) + \
                  os.popen("netstat -ano|findstr \":%s :%s :%s\""%(g_client2pop_port,g_direct_conn_port,g_client2appa_port)).read()
            os.popen("netstat -ano|findstr :%s > tmp_result " % port)
            status = self.v_file_contain_x_times_keyword('tmp_result', 'ESTABLISHED')
            if if_loginsuccess == '1' and status == 0:
                return
            elif if_loginsuccess == '0' and status == 3:
                return
            time.sleep(time_interval)
            wait_time=wait_time+time_interval
            if wait_time > max_wait_time:
                raise AssertionError("Error! Now there has %s tcp link about %s" %(status,port))
                break

    def edit_vpn_client_httpdnsiplist(self,*iplist):
        """

        :param iplist: httpdns服务器列表,可空可多个
        :return:
        """
        if len(iplist) == 0:
            str = ''
        else:
            str = '{"HttpDnsIPList": ["'
            for i in range(len(iplist)):
                if i == len(iplist) -1:
                    str = str + iplist[i] + '"]}'
                else:
                    str = str + iplist[i] + '","'
        #print str
        with open(g_client_install_path+"\\c2s_config.json",'w') as file:
            file.write(str)

if __name__ == '__main__':
    obj = VPNClient()
    
View Code

自编操作文件的库文件

# -*- coding: utf-8 -*-
# coding: unicoed_escape
# from __future__ import print_function  #修改windows下hosts文件用
import os, sys, time, stat, shutil, string, chardet, json
from VPN_Global_Variables_test import *
from VPN_Global_Variables_Common import *

# # encoding=utf8
# reload(sys)
# sys.setdefaultencoding('utf8')

import ctypes   #修改windows下hosts文件用
if sys.version_info[0] == 3:    #修改windows下hosts文件用
    import winreg as winreg
else:
    import _winreg as winreg

# 修改windows下hosts文件用
CMD                   = r"C:\Windows\System32\cmd.exe"
FOD_HELPER            = r'C:\Windows\System32\fodhelper.exe'
PYTHON_CMD            = "python"
REG_PATH              = 'Software\Classes\ms-settings\shell\open\command'
DELEGATE_EXEC_REG_KEY = 'DelegateExecute'


work_path = os.path.dirname(__file__)
os.getcwd()


class VPN_FileProcess:
    def v_file_check_isexist(self, filepath):
        """校验文件应存在

        :param filepath:文件路径
        :return: None
        """
        if not os.path.exists(filepath):
            raise AssertionError("Error! '%s' is not exist!" % filepath)

    def v_file_ifcontain_keyword(self, filepath, keyword, ifcontain="yes"):
        """校验文件中是否包含指定的关键字

        :param filepath: 文件路径

        :param keyword:  指定的关键字

        :param ifcontain: yes/no

        :return: flag(匹配到的次数)
        """
        flag = 0
        with open(filepath, 'r') as fo:
            for line in fo.readlines():
                if keyword in line.strip():
                    # print "The keyword in the line of result_file is: '%s'!" % line
                    flag = flag + 1
        if ifcontain == "yes":
            if flag == 0:
                raise AssertionError("Error! There has no '%s' in '%s'" % (keyword, filepath))
        elif ifcontain == "no":
            if flag != 0:
                raise AssertionError("Error! There has '%s' in '%s'" % (keyword, filepath))
        else:
            raise AssertionError("Error! Please input 'yes' or 'no'!")
        return flag

    def v_file_contain_x_times_keyword(self, filepath, keyword):
        flag = 0
        with open(filepath, 'r') as fo:
            for line in fo.readlines():
                line = line.decode(chardet.detect(line)['encoding'])
                if keyword in line.strip():
                    flag = flag + 1
        print "The '%s' in '%s' exist %s times!" % (keyword, filepath, flag)
        return int(flag)

    def v_log_file(self, filepath):
        """已有的打印文件内容的方法,如果文件含有中文或者编码不一致的无法打出来
        :param filepath:文件路径
        :return:
        """
        self.v_file_check_isexist(filepath)
        with open(filepath, 'r') as fo:
            for line in fo.readlines():
                line = line.decode(chardet.detect(line)['encoding'])
                print line.strip()

    def v_get_current_log_filepath(self, current_date=None):
        """获取当前client写入的日志文件路径(日志文件名称与当前日期关联)

        :param current_date: 当前日期
        :return:
        """
        if current_date == None:
            current_date = time.strftime('%Y%m%d', time.localtime(time.time()))
        current_log_file = g_client_install_path_full.strip('"') + '\log\log_' + current_date + '.log'
        return current_date, current_log_file

    def v_start_get_client_log(self):
        """获取vpn客户端当前写入日志文件的相关信息

        :return: count_line(当前日志最后一行行标),current_date_start(写入日志文件关联的日期),current_log_file(当前日志文件的路径)
        """
        count_line = 0
        current_date_start, current_log_file = self.v_get_current_log_filepath()
        # 若当前不存在该日志文件则创建
        if not os.path.exists(current_log_file):
            log_file_fw = open(current_log_file, 'w')
            log_file_fw.close()
        log_file_size = os.path.getsize(current_log_file)
        if log_file_size != 0:
            count_line = 0
            with open(current_log_file, 'r') as fo:
                for line in fo.readlines():
                    count_line = count_line + 1
        return count_line, current_date_start, current_log_file

    def v_stop_get_client_log(self, start_line, start_date, redirect_log):
        """将vpn客户端记录日志的起始位置开始的日志重定向到指定的路径

        :param start_line: 需要重定向的起始位置,由v_start_get_client_log方法返回获得

        :param start_date: 需要重定向的起始日期,由v_start_get_client_log方法返回获得

        :param redirect_log: 重定向的目标文件

        :return: None
        """
        current_date_stop, current_log_file = self.v_get_current_log_filepath()
        fw = open(redirect_log, 'w')
        count = 0
        if current_date_stop == start_date:
            with open(current_log_file, 'r') as fo:
                for line in fo.readlines():
                    count = count + 1
                    if count >= int(start_line):
                        fw.write(line)
        elif current_date_stop > start_date:
            yestday_log_file = self.v_get_current_log_filepath(start_date)[1]
            with open(yestday_log_file, 'r') as fo_yestday:
                for line in fo_yestday.readlines():
                    count = count + 1
                    if count >= int(start_line):
                        fw.write(line)
            with open(current_log_file, 'r') as fo_today:
                for line in fo_today.readlines():
                    fw.write(line)

    # 以下方法用于添加hosts解析
    def v_del_hosts_win(self, hosts_ip, hosts_domain, hosts_file=r'C:\Windows\System32\drivers\etc\hosts'):
        """用于win下删除hosts解析,不能直接使用,需要在v_hostsfile_manage_win调用,有些系统权限限制高,无法直接操作hosts
        :param hosts_ip:
        :param hosts_domain:
        :param hosts_file:
        :return:
        """
        hosts_ip_domain = hosts_ip + " " + hosts_domain
        fr = open(hosts_file, 'r')
        fw = open(hosts_file, 'w')
        # fw = open('tmp','w')
        for line in fr.readlines():
            # print line
            if '#' not in line and hosts_ip in line and hosts_domain in line:
                continue
            fw.write(line)

    def v_add_hosts_win(self, hosts_ip, hosts_domain, hosts_file):
        """用于win下删除hosts解析,不能直接使用,需要在v_hostsfile_manage_win调用,有些系统权限限制高,无法直接操作hosts"""
        hosts_ip_domain = hosts_ip + " " + hosts_domain
        fw_hosts_file = open(hosts_file, 'a')
        flag = 0
        for line in fw_hosts_file.readlines():
            if '#' not in line and hosts_ip in line and hosts_domain in line:
                flag = 1
                print('already exist!')
        if flag == 0:
            fw_hosts_file.write(hosts_ip_domain)

    def v_hosts_is_admin(self):
        """
        Checks if the script is running with administrative privileges.
        Returns True if is running as admin, False otherwise.
        """
        try:
            return ctypes.windll.shell32.IsUserAnAdmin()
        except:
            return False

    def v_hosts_create_reg_key(self, key, value):
        """
        Creates a reg key
        """
        try:
            winreg.CreateKey(winreg.HKEY_CURRENT_USER, REG_PATH)
            registry_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, REG_PATH, 0, winreg.KEY_WRITE)
            winreg.SetValueEx(registry_key, key, 0, winreg.REG_SZ, value)
            winreg.CloseKey(registry_key)
        except WindowsError:
            raise

    def v_hosts_bypass_uac(self, cmd):
        """
        Tries to bypass the UAC
        """
        try:
            self.v_hosts_create_reg_key(DELEGATE_EXEC_REG_KEY, '')
            self.v_hosts_create_reg_key(None, cmd)
        except WindowsError:
            raise

    def v_hostsfile_manage_win(self, add_or_del, hosts_ip, hosts_domain,
                               hosts_file='C:\\Windows\\System32\\drivers\\etc\\hosts'):
        """增加/删除windows下hosts中记录

        :param add_or_del: add/del
        :param hosts_ip:  添加解析的ip;若输入all,则删除hosts_domain匹配的所有解析
        :param hosts_domain: 添加解析的域名
        :param hosts_file: hosts文件,默认C:\\Windows\\System32\\drivers\\etc\\hosts
        :return:None
        """
        if not self.v_hosts_is_admin():
            print('[!] The script is NOT running with administrative privileges')
            print('[+] Trying to bypass the UAC')
            try:
                current_dir = __file__
                cmd = '{} /c {} {}'.format(CMD, PYTHON_CMD, current_dir)
                print cmd
                self.v_hosts_bypass_uac(cmd)

                print (os.popen(FOD_HELPER).read())

                sys.exit(0)
            except WindowsError:
                sys.exit(1)
        else:
            # 这里添加我们需要管理员权限的代码
            print('[+] The script is running with administrative privileges!')
            hosts_ip_domain = hosts_ip + " " + hosts_domain
            if add_or_del == 'add':
                with open(hosts_file, 'a+') as fw_hosts_file:
                    flag = 0
                    for line in fw_hosts_file.readlines():
                        if '#' not in line and hosts_ip in line and hosts_domain in line:
                            flag = 1
                            print('%s is already exist!' % hosts_ip_domain)
                    if flag == 0:
                        fw_hosts_file.write('\n%s' % hosts_ip_domain)
            elif add_or_del == 'del':
                shutil.copyfile(hosts_file, 'tmp_hosts')
                fr = open('tmp_hosts', 'r')
                with open(hosts_file, 'w') as fw:
                    for line in fr.readlines():
                        if hosts_ip == 'all':
                            if '#' not in line and hosts_domain in line:
                                continue
                            fw.write(line)
                        else:
                            if '#' not in line and hosts_ip in line and hosts_domain in line:
                                continue
                            fw.write(line)
            else:
                try:
                    winreg.DeleteKey(winreg.HKEY_CURRENT_USER, REG_PATH)
                except:
                    print "Delete the regeditkey failed!"
                finally:
                    print "Please input add/del!"
            try:
                winreg.DeleteKey(winreg.HKEY_CURRENT_USER, REG_PATH)
            except:
                print "Delete the regeditkey failed!"

    def v_channel_name_cut_end(self, channel_name):
        return channel_name.replace(".wscloudvpn.com", "")

    def v_get_dist_from_clientlog(self, filepath, src, dst, type):
        """从客户端日志文件中获取探测到的dist值
        :param filepath:日志文件路径
        :param src: 探测的起始点
        :param dst: 探测的目的
        :param type: 探测的类型,应输入client2appa/client2pop/appa2pop/pop2agent其中一个
        :return: 返回对应的dist
        """
        self.v_file_check_isexist(filepath)
        flag = 0
        with open(filepath, 'r') as fo:
            for line in fo.readlines():
                if type == "client2appa":
                    keyword = "client2appa: [client]->[%s]:" % dst
                    if keyword in line:
                        flag = 1
                        dist = line.split(':')[-1].strip()
                        # print line,"#########","The dist is:%s" % dist
                elif type == "client2pop":
                    keyword = "client2pop: [client]->[%s]:" % dst
                    if keyword in line:
                        flag = 1
                        dist = line.split(':')[-1].strip()
                        # print line, "#########", "The dist is:%s" % dist
                elif type == "appa2pop":
                    keyword = "probeinfo src[%s], dst[%s]" % (src, dst)
                    if keyword in line:
                        flag = 1
                        dist = line.split('dist')[-1].replace('[', '').replace(']', '').strip()
                        # print line, "#########", "The dist is:%s" % dist
                elif type == "pop2agent":
                    keyword = "pop2as: [%s]->[agent]:" % src
                    if keyword in line:
                        flag = 1
                        dist = line.split(':')[-1].strip()
                        # print line, "#########", "The dist is:%s" % dist
                else:
                    raise AssertionError("Error! The type please input 'client2appa/client2pop/appa2pop/pop2agent'!")

        if flag == 0:
            raise AssertionError("There is no '%s' in '%s'" % (keyword, filepath))
        return int(dist)

    def v_get_best_route_result_from_clientlog(self, filepath):
        """从客户端日志中获取,选路结果中的edge_ip和pop_ip

        :param filepath:
        :return: 选路结果中的edge_ip和pop_ip
        """
        with open(filepath, 'r') as fo:
            for line in fo.readlines():
                if "Select best route" and "edge_ip" and "origin_ip" in line:
                    edge_ip = line.split('edge_ip')[1].split('],')[0].replace('[', '')
                    pop_ip = line.split('origin_ip')[1].split('],')[0].replace('[', '')
        print edge_ip, pop_ip
        return edge_ip, pop_ip

    def v_edit_client_c2s_config_json(self, *args):
        for i in args:
            print i
        filepath = g_client_install_path + '\c2s_config.json'
        with open(filepath, 'rb') as fo:
            json1 = json.load(fo)
            print json1

    def v_wait_until_file_contains_keyword(self, filepath, keyword, match_times=1, max_waittime=30, interval=0.5):
        """等待文件中包含指定关键字N次之后停止

        :param filepath: 校验的文件路径

        :param keyword:  指定关键字

        :param match_times:  包含的次数

        :param max_waittime:  最长的等待时间

        :param interval: 检测频率

        :return: None
        """
        self.v_file_check_isexist(filepath)
        waittime = 0
        while True:
            result = os.popen('cat %s|grep \"%s\"|wc -l' % (filepath, keyword)).read()
            if int(result) == int(match_times):
                return
            waittime = waittime + interval
            time.sleep(interval)
            if waittime > max_waittime:
                break
        raise AssertionError("[%s] in [%s] match %stimes, not equal %s" % (keyword, filepath, result, match_times))

    def v_check_bestpath_in_agentlog(self, logpath, routemode, as_ip='', pop_ip='', appa_ip=''):
        """校验日志中的选路结果,选路结果关建行如:
        src AC -> 10.8.210.174 PoP -> dst DST
        src AC -> 10.8.210.173 AS -> dst DST
        src AC -> 10.8.210.167 APPA -> 10.8.210.174 PoP -> dst DST

        :param logpath: 日志路径

        :param routemode: ac_as,ac_pop,ac_appa_pop

        :param as_ip: as的ip

        :param pop_ip: pop的ip

        :param appa_ip: appa的ip

        :return: None
        """
        self.v_file_check_isexist(logpath)
        #等待日志出现PickBestPathEventCb选路结果的日志
        self.v_wait_until_file_contains_keyword(logpath, 'PickBestPathEventCb',1, 30, 0.5)
        one_log = os.popen('cat %s|grep PickBestPathEventCb').read().strip()
        print "The PickBestPath in agentlog:" % one_log
        if routemode == 'ac_as':
            match_times_inlog = self.v_file_contain_x_times_keyword(logpath,'src AC -> %s PoP -> dst DST' % as_ip)
        elif routemode == 'ac_pop':
            match_times_inlog = self.v_file_contain_x_times_keyword(logpath,'src AC -> 10.8.210.174 PoP -> dst DST' % pop_ip)
        elif routemode == 'ac_appa_pop':
            match_times_inlog = self.v_file_contain_x_times_keyword(logpath,
                                                                    'src AC -> %s APPA -> %s PoP -> dst DST' % (appa_ip, pop_ip))
        else:
            raise AssertionError("[routemode] please input [ac_as/ac_pop/ac_appa_pop]")
        if match_times_inlog == 0 :
            raise AssertionError("Error! The result in log is: %s" % one_log)

    def v_start_redirect_log(self, from_logpath, to_logpath):
        """redirect log.

        :param from_logpath: the source logpath.

        :param to_logpath: the destination logpath.

        :return:None
        """
        ip = os.popen("ifconfig eth0|grep \"inet addr\"").read().strip()
        os.popen("> %s" % to_logpath)
        os.popen("nohup tail -0f %s > %s & > /dev/null 2>&1" % (from_logpath, to_logpath))
        return ip

    def v_stop_redirect_log(self, from_logpath="tail"):
        """stop redirect log.

        :param from_logpath: the source logpath;if no input,stop all redirect log.

        :return: None
        """
        os.popen("ps -ef|grep 'tail -0f %s' |grep -v grep|awk -F ' ' '{print $2}'|xargs kill -9 > /dev/null 2>&1" % (
            from_logpath))

if __name__ == '__main__':
    obj = VPN_FileProcess()
   
View Code

猜你喜欢

转载自www.cnblogs.com/channy14/p/11547318.html
今日推荐