您当前的位置:首页 > 计算机 > 服务器 > Nginx

动态添加/删除nginx配置文件里的location python/Lua实现

时间:11-21来源:作者:点击数:

动态添加/删除nginx配置文件里的location python/Lua实现

nginx\conf.d\web_ssh.conf:

server {

    listen       82;
    server_name localhost;

    location /21899? {
        rewrite ^/21899/?$ / break;
        rewrite ^/21899/(.*)$ /$1 break;

        proxy_pass http://192.168.11.199:21899;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_read_timeout 300s;

        proxy_set_header Origin '';
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

python实现代码:

import os
import re
import traceback
import subprocess
from  multiprocessing  import  Process

port = 21897
host = "192.168.11.199"
path= r"C:\podding\common\nginx\conf.d\web_ssh.conf"
location = """
    location /%s {
        rewrite ^/%s/?$ / break;
        rewrite ^/%s/(.*)$ /$1 break;
        proxy_pass http://%s:%s/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_read_timeout 300s;
        proxy_set_header Origin '';
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
"""

def add_location(port, host, path, location):
    """
        func:向nginx配置文件中动态添加location
        params:
            port:动态端口
            host:动态IP
            path:nginx配置文件绝对路径
            location:location文本
    """
    location = location % (port, port, port, host, port)
    lines = []
    with open (path) as fp:
        for line in fp:
            lines.append(line)
    length = len(lines)
    lines.insert(length-1,location)  # 从倒数第2行开始插入想要插入的字符串
    with open(path, "w") as f:
        for line in lines:
            f.write(line)

def delete_location(port, host, path):
    """
        func:向nginx配置文件中动态删除location
        params:
            port:动态端口
            host:动态IP
            path:nginx配置文件绝对路径
    """
    with open (path) as fp:
        text = fp.read()
        print("text:%s" % text)
        pattern = re.compile(r"location /%s(.*?)%s:%s(.*?)}" % (port, host, port), re.S)  # 多行匹配
        out = re.sub(pattern, "", text)
        print("out:%s" % out)
    with open(path, 'w') as f1:
        f1.write(out)



def restart_nginx():
    logger.info("此刻运行的函数是由子进程运行,子进程ID是(%s)"  % os.getpid())
    subprocess.Popen("sudo nginx -s reload", shell=True)
    logger.info("restart nginx ok!")

def reload_nginx():
    p = Process(target = restart_nginx)  # 创建子进程实例,并关联函数
    logger.info("子进程启动...")
    p.start()
    # p.join()  # 这个方法可以等待子进程结束后再继续往下运行,通常用于进程间的同步
    logger.info("子进程结束...")


if __name__  ==  "__main__":
    add_location(port, host, path, location)
    delete_location(port, host, path)
    reload_nginx()

Lua实现代码:

local function add_location(port, host, path, location)
    --[[
        func:向nginx配置文件中动态添加location
        params:
            port:动态端口
            host:动态IP
            path:nginx配置文件绝对路径
            location:location文本
    --]]
    local location = string.format(location, port, port, port, host, port)
    line_array = {}
    for line in io.lines(path) do
        table.insert(line_array, line)
    end
    
    length = #line_array
    table.insert(line_array, length, location)  -- 从倒数第2行开始插入想要插入的字符串
    --[[print('*****')
    for i= 1, #line_array do
        print(line_array[i])
    end--]]
    
    local file, err = io.open (path,"w") --nginx使用root用户,否则无法创建
    if file==nil then
        print("Couldn't open file: "..err)
    else
        for i=1, #line_array do
            file:write(line_array[i])
            file:write("\n")
        end
        file:close()
    end
    
end


local function delete_location(port, host, path)
    --[[
        func:向nginx配置文件中动态删除location
        params:
            port:动态端口
            host:动态IP
            path:nginx配置文件绝对路径
    --]]
    local f1, errormsg = io.open(path, "r")
    if f1 == nil then
        print(errormsg)
    else
        local text = f1:read("*all")  --*all 表示读取所有的文本内容
        f1:close()
        
        --print("text:", text)
        local pattern = string.format("location /%s(.-)%s:%s(.-)}", port, host, port)
        --print("pattern:", pattern)
        
        local out = string.gsub(text, pattern, "")
        --print("out:%s", out)
        
        local f2, err = io.open (path,"w") --nginx使用root用户,否则无法创建
        f2:write(out)
        f2:close()
    end
end


port =27019
host = "192.168.11.199" 
path = "/etc/nginx/conf.d/web_ssh.conf"     
location_webssh = [[
    location /%s/ {
        rewrite ^/%s/?$ / break;
        rewrite ^/%s/(.*)$ /$1 break;
        proxy_pass http://%s:%s;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_read_timeout 300s;
        proxy_set_header Origin '';
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
]]

add_location(port, host, path, location_webssh)
delete_location(port, host, path)
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐