python程序更新实现_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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值