python修改nginx配置文件_python切割nginx配置文件的脚本

#!/usr/bin/env python

import os

import sys

def text_with_color(color,text):

def base(color,text):

color_code = {"black":30,

"red":31,

"green":32,

"yellow":33,

"blue":34,

"white":47

}

return "\033[;%sm%s\033[0m" %(color_code[color],text)

return base(color,text)

def read_nginx_file(file_name):

try:

with open(file_name) as f:

all_content = f.readlines()

except Exception,err:

print "Open nginx config file ERROR,err_msg:",err

sys.exit(3)

temp = all_content.pop()

count = 0

head = []

servers = {}

server_count = 1

while count < len(all_content):

if not all_content[count].strip().replace(" ","") == "server{":

if len(all_content[count].strip()) != 0:

head.append(all_content[count])

count += 1

else:

break

while count < len(all_content):

servers[server_count] = []

servers[server_count].append(all_content[count])

count += 1

while count < len(all_content):

if not all_content[count].strip().replace(" ","") == "server{":

if len(all_content[count].strip()) != 0:

servers[server_count].append(all_content[count])

count += 1

else:

server_count += 1

break

head.extend(["\n"," include conf.d/*.conf","\n","}"])

return head,servers

def write_main_conf_file(old_file_name,config):

os.rename(old_file_name,old_file_name + ".back")

main_file = open("nginx.conf","wb")

for i in config:

main_file.write(i)

main_file.close()

def write_server_conf_file(server):

if not os.path.exists("conf.d"):

os.mkdir("conf.d")

for i in server:

if "server_name" in i.split():

server_file = open("conf.d" + "/" + i.split()[1].strip(";") + ".conf","wb")

for i in server:

server_file.write(i)

server_file.close()

def file_format_clear(config):

count = 0

for i in config:

config[count] = i.strip()+"\n"

count += 1

space = " "

indent_count = 0

count = 0

for i in config:

if "{" in config[count]:

config[count] = space * indent_count + i

indent_count += 1

elif "}" in config[count]:

config[count] = space * (indent_count -1 ) + i

indent_count -= 1

else:

config[count] = space * indent_count + i

count += 1

if __name__ == '__main__':

file_name = "nginx.conf"

head,servers = read_nginx_file(file_name) #load nginx config file

file_format_clear(head) #format clear

for i in servers.keys():

file_format_clear(servers[i])

write_main_conf_file(file_name,head) #write main config file

for i in servers.keys(): #write server config file

write_server_conf_file(servers[i])

print text_with_color("green","Nginx config file cut success.")

print text_with_color("yellow","Please copy nginx.conf and conf.d to your nginx conf directory.")

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值