第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定

python 實(shí)現(xiàn) 2個(gè)文件替換更新

標(biāo)簽:
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


點(diǎn)擊查看更多內(nèi)容
TA 點(diǎn)贊

若覺得本文不錯(cuò),就分享一下吧!

評(píng)論

作者其他優(yōu)質(zhì)文章

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

100積分直接送

付費(fèi)專欄免費(fèi)學(xué)

大額優(yōu)惠券免費(fèi)領(lǐng)

立即參與 放棄機(jī)會(huì)
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)

舉報(bào)

0/150
提交
取消