#!/usr/bin/python
# coding: utf-8
import os
import re
import sys
import xlrd
SERVERS_EXCELFILE = u‘/etc/subversion/平台服/平台服务器资料.xls‘
TOP_DIR = os.path.dirname(os.path.abspath(sys.argv[0]))
HOSTFILE = os.path.join(TOP_DIR,‘hosts‘)
serverlist = []
sheets = {
u"平台网站":[1,3,5,6,7],
#u"平台接口":[1,2,5,6,9],
}
def sheet_parse(excelfile,sheetname,rols):
global serverlist
sheet = excelfile.sheet_by_name(sheetname)
for row in range(rols[0],sheet.nrows):
wan_ip = sheet.cell_value(row,rols[1])
lan_ip = sheet.cell_value(row,rols[2])
if not re.match(r‘^[1-9]{0,2}\.[0-9]{1,3}‘,wan_ip):
wan_ip = 0
if not re.match(r‘^[1-9]{0,2}\.[0-9]{1,3}‘,lan_ip):
lan_ip = 0
if wan_ip or lan_ip:
server = ‘%s %s %d %s\n‘ % (
str(wan_ip).split()[0],
str(lan_ip).split()[0],
int(sheet.cell_value(row,rols[3])),
sheet.cell_value(row,rols[4])
)
serverlist.append(server)
def main():
excelfile = xlrd.open_workbook(SERVERS_EXCELFILE)
if os.path.exists(HOSTFILE):
os.remove(HOSTFILE)
for sheetname in sheets.keys():
sheet_parse(excelfile,sheetname,sheets[sheetname])
try:
hostsfile = open(HOSTFILE,‘w‘)
hostsfile.writelines(serverlist)
finally:
hostsfile.close()
if __name__ == ‘__main__‘:
main()
原文地址:http://19921009.blog.51cto.com/8714442/1703058