標籤:
#!/usr/bin/env pythonimport osimport sysdef 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 += 1if __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.")
python切割nginx設定檔的指令碼