sm702 发表于 2018-8-13 09:56:35

python 实现 2个文件替换更新

  业务需求: ansible同步中,hosts需要用变化的zk-hosts文件来更新。并且在指定位置去添加和删除,本例中添加和删除为这个项目。
  思路: 将 每个 方括号开头项目作为一个字典的 key ,其下的 IP 作为一个 value 。 将其制作为一个字典 。 更新时,先去找到 [ ] 项目名称,后去更新其的值, 包括删除,增加,判断是否存在。
  $ cat hosts
  
  192.168.3.3
  
  192.168.1.137
  
  192.168.1.61
  192.168.1.62
  192.168.1.63
  
  192.168.1.158
  192.168.1.159
  
  192.168.1.8
  $ cat zk-hosts变化的文件
  
  -192.168.1.61
  -192.168.1.62
  10.0.0.1
  10.0.0.2
  #源代码
  #!/usr/bin/env python
  import os,sys,re
  #os.system('cat /root/hosts/test/hosts | tr '\n' ' ' | xargs echo| tr '[' '\n' | tr ']' ' ' &>hosts.txt')
  def update_ip(*project):
  project=raw_input("pleas input project ")
  os.system('/bin/bash a.sh')#
  d={}
  ip=[]
  f=open('hosts.txt','a+')
  a=f.readlines()
  f.close()
  for line in a:
  env=(line.split())
  iplist=line.split()
  #if env==project:
  d=iplist
  #print d
  #print project
  ciplist=d
  #print ciplist
  #
  zk=[]
  z=open('zk-hosts')
  for hosts in z.readlines():
  hosts=hosts.strip('\n')
  zk.append(hosts)
  zk.pop(0)
  #print zk
  #
  for i in zk:
  #print i
  if i in ciplist:
  print "%s is exists" % i
  elif re.match(r'-(.*)',i):
  i=i.lstrip('-')
  if i in ciplist:
  ciplist.remove(i)
  else:
  ciplist.append(i)
  #print ciplist
  #print d.items()
  b=open('hosts','a+')
  b.truncate()
  for key in d:
  b.write('['+key+']'+'\n')
  for m in d:
  print m
  b.write(m+'\n')
  b.close()
  update_ip()
  #python脚本中调用的 shell 脚本。
  $ cat a.sh
  #!/bin/bash
  cat /root/hosts/test/hosts | tr '\n' ' ' | xargs echo| tr '[' '\n' | tr ']' ' ' &>hosts.txt
  sed -i '1d' hosts.txt
  #cat /root/hosts/test/zk-hosts | tr '\n' ' ' | xargs echo | tr '[' '\n' | tr ']' ' ' &>zk-hosts.txt
  #sed -i '1d' zk-hosts.txt
  执行后结果
  $ cat hosts
  
  192.168.3.3
  
  192.168.1.137
  
  192.168.1.63
  10.0.0.1
  10.0.0.2
  
  192.168.1.8
  
  192.168.1.158
  192.168.1.159
页: [1]
查看完整版本: python 实现 2个文件替换更新