亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

python 實現 2個文件替換更新

標簽:
Python

业务需求: 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


點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消