写个脚本,通过Nginx的http_access_module模块实现基于IP的访问控制。

通过tkinter实现的客户端用于客服人员进行IP绑定,python脚本读取写入配置文件,allowip.con需要在nginx配置文件的Location引入。功能虽实现了,但并不优雅,进一步升级可以通过nginx+lua去做。

执行脚本

import time
import datetime
import os
import pymysql

def watch_file(filename):
    while True:
        conn = pymysql.connect('xx.xx.xx.xx', '用户名', '密码', '数据库')
        # conn = pymysql.connect('192.168.3.2', 'root', '123456', 'pay')
        cursor = conn.cursor()
        sql = "select * from ip where 1 order by id desc"
        # sql = "select * from ip where 1 order by id desc"
        cursor.execute(sql)
        res = cursor.fetchone()

        with open(filename, 'r+', encoding='utf-8') as f:
            f.seek(0,os.SEEK_SET) # 设置偏移从文件头开始写
            info = f.read()
            if not info.find(res[1]) > 0:
               status = f.write('\nallow ' + res[1]+';') # 换行

        res = os.system("/usr/bin/nginx -s reload")
        time.sleep(30)


if __name__ == '__main__':
    filename = '/www/server/allow_ip.conf'
    watch_file(filename)

allow_ip.conf写入的ip

allow x.x.x.x;
allow x.x.x.x;
allow x.x.x.x;