关于python:python-获取vhost-servername-document

55次阅读

共计 2219 个字符,预计需要花费 6 分钟才能阅读完成。

# -*- coding: utf-8 -*-
import re
import os

def GetVhostList(file):
  with open(file, 'r') as f:
    page = f.read()
    reg = r'\n<VirtualHost \*:80>(.*?)</VirtualHost>'
    content = re.compile(reg,re.DOTALL)
    vhostlist = content.findall(page)
    return vhostlist

def GetDocumentRoot(vhost):
  reg_doc = r'\n\s+DocumentRoot (.*?)\n'
  content = re.compile(reg_doc,re.DOTALL)
  doc = content.findall(vhost)[0].strip()
  return doc

def GetServerName(vhost):
  reg_servername = r'\n\s+ServerName (.*?)\n'
  content = re.compile(reg_servername,re.DOTALL)
  servername = content.findall(vhost)[0].strip()
  return servername

def GetServerAlias(vhost):
  serveralias_list = []
#  reg_serveralias = r'\n\s+ServerAlias\s(.*?)\.com'
  reg_serveralias = r'\n\s+ServerAlias (.*?)\n'
  content = re.compile(reg_serveralias,re.DOTALL)
  serveralias = re.findall(content,vhost)
  serveralias_list.append(serveralias)
  return serveralias_list

def GetVhostKey(vhostlist):
  vhostkey_list = []
  for str_vhost in vhostlist:
    dit = {'DocumentRoot': GetDocumentRoot(str_vhost), 'ServerName': GetServerName(str_vhost),'ServerAlias': GetServerAlias(str_vhost)}
    vhostkey_list.append(dit)
  return vhostkey_list

def GetServernameDoc(vhostkey_list):
  server_document_list = []
  for servername in vhostkey_list:  
    dit_server = {'DocumentRoot': servername['DocumentRoot'],'Server': servername['ServerName']}
    server_document_list.append(dit_server)
    if servername['ServerAlias']:
      for serveralias in servername['ServerAlias']:
        dit_serveralias = {'DocumentRoot': servername['DocumentRoot'],'Server': serveralias}
        server_document_list.append(dit_serveralias)
  return server_document_list
 
#def split_list_dit(mylist):
#  list_first = []
#  for l in mylist:
#    if l['Server'].count('.') == 2:
#      dit = {'DomainName': l['Server'].split('.',1)[0], 'Domain': l['Server'].split('.',1)[1], 'DocumentRoot': l['DocumentRoot']}
#      list_first.append(dit)
#    if l['Server'].count('.') == 1:
#      dit = {'DomainName': '','Domain': l['Server'],'DocumentRoot': l['DocumentRoot']}
#      list_first.append(dit)
#  return list_first

 

def main():
  file = "/root/httpd.conf"
  mylist = GetVhostList(file)
  myvhostkey = GetVhostKey(mylist)
  print myvhostkey
#  server_list = GetServernameDoc(myvhostkey)
#  split_server_list = split_list_dit(server_list)
#  sort_domain = sorted(split_server_list, key=lambda l: l['Domain'])
#  for l in sort_domain:
#    print l['DomainName'] + '.' + l['Domain'],l['DocumentRoot']
#    print l['DocumentRoot']

if __name__ == "__main__":
  main()

正文完
 0