3.函数、递归、模块

查询、添加、删除配置文件中的ip

查询

添加

将域名和ip分为三段,域名前、本域名、域名后,写到新配置文件中,

当检测新配置文件没错误时,备份配置文件,将新配置文件重命名为配置文件名,重启服务器

import shutil
	
def fetch(domain):
	find_domain = "backend %s" % domain
	is_find_domain = False
	server_list = []
	with open('haproxy.conf','r') as r:
		for line in r:#前面排除错误的,最后是正确的
			curr =  line.strip()
			#print curr
			if curr == find_domain:
				#print True
				is_find_domain = True
			elif is_find_domain and curr.startswith("backend"):
				break
			elif is_find_domain and curr:
				server_list.append(curr)
	return server_list

def add(domain,server):
	server_list = fetch(domain)
	print server_list
	if not server_list:#如果列表为空,则添加至最后
		write_domain = "\nbackend %s\n" % domain
		write_server = "\t%s\n" % server
		with open('haproxy.conf','a') as a:
			a.write(write_domain)
			a.write(write_server)
		pass
	elif server not in server_list:
		server_list.append(server)
		find_domain = "backend %s" % domain
		is_find_domain = False
		with open('haproxy.conf','r') as r,open('haproxy.conf-new','w') as w:
			for line in r:
				curr = line.strip()
				# print curr
				if curr == find_domain:#如果找到,则将该域名及其所属ip写入新配置文件
					# print True
					is_find_domain = True
					w.write("%s\n" % find_domain)
					for server_temp in server_list:
						w.write("\t%s\n" % server_temp)
				elif is_find_domain and curr.startswith("backend"):
					is_find_domain = False
					w.write(line)

				elif curr not in server_list and curr:
					w.write(line)
	pass
#分三段,域名前、本域名、域名后
hosts = fetch('news.baidu.com')
print hosts
#备份配置文件
shutil.copy('haproxy.conf',"haproxy.conf.bak")
add('news.baidu.com','server 127.0.0.23')
#添加过后,若检查新配置语法正确,则将新配置文件中的内容写到配置文件中
shutil.copy('haproxy.conf-new',"haproxy.conf")

删除

函数

def addNum(a,b):
	return a + b

print map(addNum,[1,2,3],[4,5,6])

def reduce1(a,b):
	return a + b
print reduce(reduce1,[1,2,3],10)

def filter1(a):
	if a:
		return True
print filter(filter1,[4,5,0,[],'',6])





#斐波那契数列		0 1 1 2 3 5 求和大于1000时的位数

def feiboOne(num):
	if num <= 1:
		return num
	else:
		return feiboOne(num - 1) + feiboOne(num - 2)

def feibo_pos(all,sum=0,pos=-1):
	while sum < all:
		pos += 1
		sum += feiboOne(pos)
		#print pos
	return pos

all = 100000
print feibo_pos(all)

 模块

相关功能的代码集合

.py文件、文件夹__init__.py

os

sys

json、pickle

subprocess执行系统命令、checkoutoutput、popen

paramikoe

log日志模块很重要,记录操作状态,在线排查问题,日志要切割

 

 

 

 

推荐书籍:林达:近距离看美国

posted @ 2017-10-30 21:54  dlgd  阅读(116)  评论(0编辑  收藏  举报