python read nginx Virtual Host Configuration database insert myqsql

## get nginx virtual host configuration file path and file name ####### 
## HTTPS: //github.com/fatiherikli/nginxparser ######### PIP install nginxparser ##### ## 
DEF getconf (): 
    from the Load nginxparser Import 
    filepath = "/ etc / nginx / conf" 
    for parent, dirnames, filenames in os.walk (filepath): 
        for filename in the SET (filenames): 
            File = (os.path. the Join (parent, filename)) 
            Print (File) 
            the try: 
                Data = Load (Open (File)) 
                T = GetDict (Data, List ()) 
                D = dict () 
                D [ "Server"] = List () 
                D [ " the listen "] = List () 
                D [" upstream "] = List ()
                for x in T:
                    if x["key"] == "upstream":
                        D["upstream"].append(x["value"])
                    elif x["key"] == "server_name":
                        D["server_name"] = x["value"]
                    elif x["key"] == "server":
                        try:
                            D["server"].append(x["value"])
                        except:
                            pass
                    elif x["key"] == "listen":
                        D["listen"].append(x["value"]) 
                 Pass
            the except:
                yield D

                Print ( "configuration file:" + File)


########## recursive multilevel list split the list converted to dictionary 
DEF GetDict (X, L = list ()): 
    A = [ "Key", "value"] 
    for I in X: 
        IF the isinstance (I, List): 
            IF the isinstance (I [0], List): 
                for Y in I: 
                    # Print ( "#######:", Y) 
                    GetDict (Y, L) 
            the else: 
                # Print ( " xxxxxxxxxxxxxx: ", dict (ZIP (A, I))) 
                l.append (dict (ZIP (A, I))) 
        the else: 
            l.append (dict (ZIP (A, X))) 
    return L 


#### obtaining the configuration database ### is inserted ######### 
DEF mysqlConfig (SQL): 
    Import pymysql 
    USERNAME = "OPS" 
		PASSWORD = "123456"
    HOST = "192.168.1.1"
    DATABASE = "op_nginx"
    dbconfig = pymysql.connect(HOST, USERNAME, PASSWORD, DATABASE)
    try:
        print(sql)
        cursor = dbconfig.cursor()
        try:
            cursor.execute(sql)
            dbconfig.commit()
            return cursor
        except Exception as e:
           pass
    except Exception as err:
        print(err)
				
def createNginxConfigtab():
    sql = """CREATE TABLE  if not exists  virtual_host (
             env CHAR(32) NOT NULL,
             upstreamname CHAR(128),
             domainname CHAR(200),
             frontport CHAR(128),
             backendip CHAR(128)
             )"""
    mysqlConfig(sql)
createNginxConfigtab()


###########数据插入###########
def nginxtbale(env, upname, dominame, frontport, backendip):
    try:
        sql = """INSERT INTO virtual_host(env,upstreamname,
                         domainname,  frontport, backendip)
                         VALUES ('{}','{}', '{}','{}','{}')""".format(env, upname, dominame, frontport,
                                                                      backendip)
        mysqlConfig(sql)
    except Exception as e:
DEF insertNginxConfig ():
####### to read out the configuration database #############
        Print (E)
        If an error occurs # rollback


 
    for i in getconf (): 
        the try:
            nginxtbale("test", ",".join(list(set((i["upstream"])))), i["server_name"].replace(" ", ","),
                       ",".join(i["listen"]), ",".join(i["server"]))
        except:
             print(i)
insertNginxConfig()

#########


Guess you like

Origin blog.51cto.com/breaklinux/2402003