自動放行nginx後臺訪問ip

因爲公司外網地址是動態變化的,但又必須作到僅公司能訪問,如下是實現方式python

獲取公司外網ipmysql

#!/usr/local/bin/python3
# coding:utf-8


# ====================================================
# Author: chang - EMail:changbo@hmg100.com
# Last modified: 2017-04-28
# Filename: getoutip.py
# Description: get out ip,base requests ,json, time, pymysql, socket
# blog:http://www.cnblogs.com/changbo
# ====================================================

# import socket
# import requests
# import json
import time
import pymysql
import socket


port = xxxx
host = 'x.x.x.x'


def getOut():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((host, port))
    data = 'hi'
    s.send(str(data).encode('utf-8'))
    results = s.recv(1024)
    getip = str(results, 'utf-8')
    s.close()

    nowtime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
    db = pymysql.connect('x.x.x.x', 'root', 'xxxxx', 'yunwei')
    # print(nowtime)
    # url = "https://ipinfo.io"
    
    iplist = []
    # r = requests.get(url)
    # getip = json.loads(r.text)
    
    sql1 = 'select ip from wan_ip'
    sql2 = "INSERT INTO wan_ip(ip, time) VALUES('%s', '%s')" % (getip, nowtime)
    cursor = db.cursor()
    cursor.execute(sql1)
    datad = cursor.fetchall()
    for i in datad:
        iplist.append(i[0])
    
    if getip not in iplist:
        cursor.execute(sql2)
        db.commit()
        db.close()
      
def getOutwan():
    time.sleep(120)
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((host, port))
    data = 'hi'
    s.send(str(data).encode('utf-8'))
    results = s.recv(1024)
    getip = str(results, 'utf-8')
    s.close()

    nowtime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
    db = pymysql.connect('x.x.x.x', 'xxxx', 'xxxx', 'yunwei')
    # print(nowtime)
    # url = "https://ipinfo.io"

    iplist = []
    # r = requests.get(url)
    # getip = json.loads(r.text)

    sql1 = 'select ip from wan_ip'
    sql2 = "INSERT INTO wan_ip(ip, time) VALUES('%s', '%s')" % (getip, nowtime)
    cursor = db.cursor()
    cursor.execute(sql1)
    datad = cursor.fetchall()
    for i in datad:
        iplist.append(i[0])

    if getip not in iplist:
        cursor.execute(sql2)
        db.commit()
        db.close()

if __name__ == '__main__':
    getOut()
    getOutwan()

 發送公網外網ipnginx

#!/usr/local/bin/python3

import socket import threading # ==================================================== # Author: chang - EMail:changbo@hmg100.com # Last modified: 2017-04-28 # Filename: sendoutip.py # Description: send u out ip ,base socket # blog:http://www.cnblogs.com/changbo # ====================================================
 port = xxxx host = 'x.x.x.x'


def sendOut(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host, port)) s.listen(5) while True: connection, address = s.accept() ip, _ = address ip = (str(ip)).encode('utf-8') while True: try: data = connection.recv(1024) if not data: break connection.send(ip) except Exception as e: pass
            # s.close()
 connection.close() continue s.close() if __name__ == '__main__': t = threading.Thread(target=sendOut) t.start() 

 

自動修改nginx可訪問ipweb

#!/usr/local/bin/python3 # coding:utf-8

# ==================================================== # Author: chang - EMail:changbo@hmg100.com # Last modified: 2017-04-28 # Filename: changehoutaiip.py # Description: change nginx access web ip,base re ,pymysql, subprocess # blog:http://www.cnblogs.com/changbo # ====================================================

import re import pymysql import subprocess def GetNginxAddr(): with open('/var/openresty/nginx/conf/nginx.conf') as f: lines = f.readlines() for line in lines: temline = line.split(')') if '$remote_addr !~* ' in temline[0] and '#' not in temline[0]: ipadd = re.findall(r'\d+.\d+.\d+.\d+', temline[0]) return ipadd[0] # print(GetNginxAddr())


def GetNowWanAddr(): db = pymysql.connect('x.x.x.x', 'xxxx', 'xxxx', 'yunwei') sql1 = 'select ip from wan_ip ORDER by id desc limit 1' cursor = db.cursor() cursor.execute(sql1) datad = cursor.fetchone() datad = '%s' % datad return datad # print(GetNowWanAddr())
 oldip = GetNginxAddr() newip = GetNowWanAddr() # print(oldip, newip)


def alter(file, oldstr, newstr): file_data = ""
    if oldstr != newstr: with open(file) as f: lines = f.readlines() for line in lines: temline = line.split(')') if '$remote_addr !~* ' in temline[0] and '#' not in temline[0]: line = line.replace("if ($remote_addr !~* '" + oldip + "'){", "if ($remote_addr !~* '" + newip + "'){") file_data += line with open(file, "w") as f: f.write(file_data) subprocess.Popen("/var/openresty/nginx/sbin/nginx -s reload", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) else: pass alter("/var/openresty/nginx/conf/nginx.conf", oldip, newip)

 

END!sql

相關文章
相關標籤/搜索