Python3.5编程实现修改IIS WEB.CONFIG的方法示例


Posted in Python onAugust 18, 2017

本文实例讲述了Python3.5编程实现修改IIS WEB.CONFIG的方法。分享给大家供大家参考,具体如下:

#!/usr/bin/env python3.5
# -*- coding:utf8 -*-
from xml.etree.ElementTree import ElementTree,Element
def read_xml(in_path):
  """
  读取并解析XML文件
  :param in_path: XML路径
  :return:
  """
  tree = ElementTree()
  tree.parse(in_path)
  return tree
def write_xml(tree,out_path):
  """
  将XML文件写出
  :param tree:
  :param out_path:写出路径
  :return:
  """
  tree.write(out_path,encoding="utf-8",xml_declaration=True)
def if_match(node,kv_map):
  """
  判断某个节点是否包含所有传入参数属性
  :param node: 节点
  :param kv_map: 属性及属性值组成的MAP
  :return:
  """
  for key in kv_map:
    if node.get(key) != kv_map.get(key):
      return False
    return True
def find_nodes(tree,path):
  """
  查找某个路径匹配的所有节点
  :param tree:XML树
  :param path:节点路径
  :return:
  """
  return tree.findall(path)
def get_node_by_keyvalue(nodelist,kv_map):
  """
  根据属性及属性值定位符合的节点,返回节点
  :param nodelist: 节点列表
  :param kv_map: 匹配属性及属性值MAP
  :return:
  """
  result_nodes =[]
  for node in nodelist:
    if if_match(node,kv_map):
      result_nodes.append(node)
  return result_nodes
def change_node_properties(nodelist,kv_map,is_delete =False):
  """
  修改、增加、删除 节点的属性及属性值
  :param nodelist: 节点列表
  :param kv_map: 属性及属性值MAP
  :param is_delete:
  :return:
  """
  for node in nodelist:
    for key in kv_map:
      if is_delete:
        if key in node.attrib:
          del node.attrib[key]
      else:
        node.set(key,kv_map.get(key))
def change_node_text(nodelist,text,is_add=False,is_delete=False):
  """
  改变、增加、删除一个节点的文本
  :param nodelist: 节点列表
  :param text: 更新后的文本
  :param is_add:
  :param is_delete:
  :return:
  """
  for node in nodelist:
    if is_add:
      node.text += text
    elif is_delete:
      node.text = ""
    else:
      node.text = text
def create_node(tag,property_map,content):
  """
  新造一个节点
  :param tag:节点标签
  :param property_map:属性及属性值MAP
  :param content: 节点闭合标签里的文件内容
  :return:新节点
  """
  element =Element(tag,property_map)
  element.text =content
  return element
def add_child_node(nodelist,element):
  """
  给一个节点添加子节点
  :param nodelist: 节点列表
  :param element: 子节点
  :return:
  """
  for node in nodelist:
    node.append(element)
def del_node_by_tagkeyvalue(nodelist,tag,kv_map):
  """
  同过属性及属性值定位一个节点,并删除之
  :param nodelist: 父节点列表
  :param tag: 子节点标签
  :param kv_map: 属性及属性值列表
  :return:
  """
  for parent_node in nodelist:
    childree = parent_node.getchildren()
    for child in childree:
      if child.tag == tag and if_match(child,kv_map):
        parent_node.remove(child)
def config_file_rw(file):
  """
  对XML配置文件进行修复以满足适应IIS
  :param file: 目标文件
  :return:
  """
  import re
  x =re.compile("<ns0:")
  y = re.compile("</ns0:")
  z = re.compile("xmlns:ns0")
  with open(file,"r",encoding="utf-8") as f:
    txt = f.readlines()
    for i, line in enumerate(txt):
      if x.search(line):
        txt[i] = x.sub("<", line)
      elif y.search(line):
        txt[i] = y.sub("</", line)
      elif z.search(line):
        txt[i] = "<configuration>\n"
  with open(file,"w",encoding="utf-8") as fw:
    fw.writelines(txt)
    fw.close()
    print("配置文件%s,修改成功!"%file)
if __name__ == "__main__":
  #1. 读取xml文件
  tree = read_xml("web.config")
  # 找到父节点
  print()
  nodes = find_nodes(tree, "connectionStrings/")
  # 通过属性准确定位子节点
  result_nodes =(get_node_by_keyvalue(nodes,{"name":"strConnection_HuaChenShiYou"}))
  # 修改节点属性
  change_node_properties(result_nodes,{"connectionString":"UwreW/Obe4fGk2CFW4uE6iZWaPAVn0nePXIrtNRApxEGLv6SHetFg6b%2BMLFhg9myAr2EI2b3FgHtKHOKVcjz5DPoV8%2BMAvpzqlEZP2JZqrVEofP3AulFUZbTLfmndYFRqIytlxSCeHr2A79EWHH9/xg0eSgsdvWd"})
  # #2. 属性修改
  # #A. 找到父节点
  # nodes = find_nodes(tree, "processers/processer")
  # #B. 通过属性准确定位子节点
  # result_nodes = get_node_by_keyvalue(nodes, {"name":"BProcesser"})
  # #C. 修改节点属性
  # change_node_properties(result_nodes, {"age": "1"})
  # #D. 删除节点属性
  # change_node_properties(result_nodes, {"value":""}, True)
  #
  # #3. 节点修改
  # #A.新建节点
  # a = create_node("person", {"age":"15","money":"200000"}, "this is the firest content")
  # #B.插入到父节点之下
  # add_child_node(result_nodes, a)
  #
  # #4. 删除节点
  #  #定位父节点
  # del_parent_nodes = find_nodes(tree, "processers/services/service")
  #  #准确定位子节点并删除之
  # target_del_node = del_node_by_tagkeyvalue(del_parent_nodes, "chain", {"sequency" : "chain1"})
  #
  # #5. 修改节点文本
  #  #定位节点
  # text_nodes = get_node_by_keyvalue(find_nodes(tree, "processers/services/service/chain"), {"sequency":"chain3"})
  # change_node_text(text_nodes, "new text")
  #
  # #6. 输出到结果文件
  write_xml(tree, "new.config")
  config_file_rw("new.config")

希望本文所述对大家Python程序设计有所帮助。

Python 相关文章推荐
使用Python的Tornado框架实现一个一对一聊天的程序
Apr 25 Python
python模拟Django框架实例
May 17 Python
Python简单计算给定某一年的某一天是星期几示例
Jun 27 Python
Python面向对象之类和对象属性的增删改查操作示例
Dec 14 Python
对python实现二维函数高次拟合的示例详解
Dec 29 Python
Python对象与引用的介绍
Jan 24 Python
Python对象转换为json的方法步骤
Apr 25 Python
python被修饰的函数消失问题解决(基于wraps函数)
Nov 04 Python
python GUI库图形界面开发之PyQt5控件QTableWidget详细使用方法与属性
Feb 25 Python
Python实例教程之检索输出月份日历表
Dec 16 Python
如何用Django处理gzip数据流
Jan 29 Python
python计算列表元素与乘积详情
Aug 05 Python
Python 中 Virtualenv 和 pip 的简单用法详解
Aug 18 #Python
Python3编程实现获取阿里云ECS实例及监控的方法
Aug 18 #Python
浅谈django开发者模式中的autoreload是如何实现的
Aug 18 #Python
Python绑定方法与非绑定方法详解
Aug 18 #Python
python字典DICT类型合并详解
Aug 17 #Python
Python时间的精准正则匹配方法分析
Aug 17 #Python
Python实现运行其他程序的四种方式实例分析
Aug 17 #Python
You might like
php巧获服务器端信息
2006/12/06 PHP
在数据量大(超过10万)的情况下
2007/01/15 PHP
php array_merge下进行数组合并的代码
2008/07/22 PHP
PHP 函数语法介绍一
2009/06/14 PHP
表格展示无限级分类(PHP版)
2012/08/21 PHP
php获取通过http协议post提交过来xml数据及解析xml
2012/12/16 PHP
PHP设计模式之状态模式定义与用法详解
2018/04/02 PHP
使用PHPUnit进行单元测试并生成代码覆盖率报告的方法
2019/03/08 PHP
XAMPP升级PHP版本实现步骤解析
2020/09/04 PHP
理解Javascript_07_理解instanceof实现原理
2010/10/15 Javascript
function foo的原型与prototype属性解惑
2010/11/19 Javascript
javascript window.open打开新窗口后无法再次打开该窗口问题的解决方法
2014/04/12 Javascript
JavaScript的Backbone.js框架入门学习指引
2016/05/07 Javascript
JS简单获取当前年月日星期的方法示例
2017/02/07 Javascript
BootStrap Datetimepicker 汉化的实现代码
2017/02/10 Javascript
jQuery插件HighCharts绘制2D柱状图、折线图和饼图的组合图效果示例【附demo源码下载】
2017/03/09 Javascript
ionic 自定义弹框效果
2017/06/27 Javascript
写一个Vue loading 插件
2020/11/09 Javascript
在Python的Flask框架中实现全文搜索功能
2015/04/20 Python
python中快速进行多个字符替换的方法小结
2016/12/15 Python
Python的numpy库中将矩阵转换为列表等函数的方法
2018/04/04 Python
详解Python requests 超时和重试的方法
2018/12/18 Python
Python如何使用k-means方法将列表中相似的句子归类
2019/08/08 Python
python+rsync精确同步指定格式文件
2019/08/29 Python
Python 过滤错误log并导出的实例
2019/12/26 Python
python模拟实现分发扑克牌
2020/04/22 Python
python 下载文件的几种方法汇总
2021/01/06 Python
橄榄树药房:OLIVEDA
2019/09/01 全球购物
大学生家政服务项目创业计划书
2014/01/30 职场文书
幼儿园中班上学期评语
2014/04/18 职场文书
医德考评自我评价
2014/09/14 职场文书
2014年社区宣传工作总结
2014/12/02 职场文书
文明单位创建材料
2014/12/24 职场文书
个人简历自我评价怎么写
2015/03/10 职场文书
大学团日活动总结书
2015/05/11 职场文书
使用MybatisPlus打印sql语句
2022/04/22 SQL Server