python 實現 2個文件替換更新
業務需求: ansible同步中,hosts需要用變化的zk-hosts文件來更新。並且在指定位置去添加和刪除,本例中添加和刪除為[prod]這個項目。
思路: 將 每個[prod] 方括號開頭項目作為一個字典的 key ,其下的 IP 作為一個 value 。 將其制作為一個字典 。 更新時,先去找到 [ ] 項目名稱,後去更新其的值, 包括刪除,增加,判斷是否存在。
[root@hello test]$ cat hosts
[test]
192.168.3.3
[pre]
192.168.1.137
[prod]
192.168.1.61
192.168.1.62
192.168.1.63
[prod_cli]
192.168.1.158
192.168.1.159
[prod_admin]
192.168.1.8
[root@hello test]$ cat zk-hosts 變化的文件
[all]
-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()[0])
iplist=line.split()[1:]
# if env==project:
d[env]=iplist
#print d
#print project
ciplist=d[project]
#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[key]:
print m
b.write(m+‘\n‘)
b.close()
update_ip()
#python腳本中調用的 shell 腳本。
[root@hello test]$ 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
執行後結果
[root@hello test]$ cat hosts
[test]
192.168.3.3
[pre]
192.168.1.137
[prod]
192.168.1.63
10.0.0.1
10.0.0.2
[prod_admin]
192.168.1.8
[prod_cli]
192.168.1.158
192.168.1.159
本文出自 “手有余香” 博客,請務必保留此出處http://19941018.blog.51cto.com/11889001/1983888
python 實現 2個文件替換更新