python ipset管理 增删白名单的方法

作者:云中不知人 时间:2021-02-10 17:38:19 

为方便用ipset 来管理防火墙,写了下面Ipset类来对Ip进行管理


#!/usr/bin/env python
# coding: utf-8

import MySQLdb
import MySQLdb.cursors
import subprocess
import logging
import re,os
import xml.sax

class XMLHandler(xml.sax.ContentHandler):
'''
用来解析ipset数据
'''
def __init__(self):
 self.current_tag = ""
 self.current_set = ""
 self.mapping = {}

def startElement(self, name, attributes):
 self.current_tag = name
 if name == 'ipset':
  self.current_set = attributes['name']
  self.mapping[self.current_set] = []

def characters(self, data):
 if self.current_tag == 'elem' and data!='\n':
  self.mapping[self.current_set].append(data)

def endElement(self, name):
 if name == 'ipset':
  self.current_set = ''

def getData(self):
 return self.mapping

class IpsetPool(object):
def __init__(self):
 self.msg = []
 self.config = '/etc/sysconfig/ipset'
 self.logger_file = '/data/logs/ipset.log'
 self.ipsets = ['manage','center','project']
 self.log = self.mylog()
 self.ipset_data = self.getIpsetData(XMLHandler)

def sub_call(self,run_cmd, **kwargs):
 p = subprocess.Popen(
  run_cmd,
  shell=True,
  stdin=subprocess.PIPE,
  stdout=subprocess.PIPE,
  stderr=subprocess.PIPE,
  **kwargs)
 outdata, errdata = p.communicate()
 retcode = p.wait()
 self.msg.append((False,errdata) if retcode != 0 else (True,outdata))
 return retcode, outdata, errdata

@staticmethod
def querydb(sql):
 host = "192.168.59.128"
 user = "dev"
 passwd = "123456"
 db = "gmweb_res"
 conn = MySQLdb.connect(
  host=host,
  user=user,
  passwd=passwd,
  db=db,
  charset="utf8",
  cursorclass=MySQLdb.cursors.DictCursor)
 cursor = conn.cursor()
 cursor.execute(sql)
 rs = cursor.fetchall()
 cursor.close()
 conn.commit()
 conn.close()
 return rs

def getManageIps(self):
 sql = "select * from host where state not in (6) and `use` REGEXP ',2$|^2,|^2$|,2,';"
 return [x["ip1"] for x in self.querydb(sql)]

def getProjectIps(self):
 from jgconf.models import projectConf
 return [i['saltIp'] for item in projectConf.objects.all() for i in item.getSaltServer()]

def checkAddrIsIn(self, ip, setname):
 '''
 判断ip是否在某个set中
 '''
 if ip in self.ipset_data[setname]:
  return True
 else:
  return False

def getIpsetData(self,xml_handler):
 '''
 获取机器上当前的ipset配置数据
 '''
 xh = xml_handler()
 xml.sax.parseString(self.sub_call('ipset list -o xml')[1], xh)
 return xh.getData()
def createSet(self,setname):
 self.log.info('create {0} set'.format(setname))
 set_cmd = 'ipset create {0} hash:ip'.format(setname)
 return self.sub_call(set_cmd)

def renderSetFile(self):
 '''
 重导配置
 '''
 self.sub_call('ipset save > {0}'.format(self.config))

def createIpsets(self):
 for ipset in self.ipsets:
  self.createSet(ipset)

def addIps2Set(self,setname,ips):
 if setname not in self.ipsets:
  self.log.error('invalid set name!')
  return False
 if not self.ipset_data.has_key(setname):
  self.createSet(setname)
 for ip in ips:
  if not self.checkAddrIsIn(ip,setname):
   self.log.info('add {0} {1}'.format(setname,ip))
   self.sub_call('ipset -A {0} {1}'.format(setname,ip))
 self.renderSetFile()
def delIpsFromSet(self,setname,ips):
 self.log.info(ips)
 if setname in self.ipsets and self.ipset_data.has_key(setname):
  for ip in ips:
   if self.checkAddrIsIn(ip,setname):
    self.log.info('delete {0} {1}'.format(setname,ip))
    self.sub_call('ipset -D {0} {1}'.format(setname,ip))
 self.renderSetFile()
def mylog(self):
 logger_dir = os.path.split(self.logger_file)[0]
 if not os.path.exists(logger_dir):
  os.makedirs(logger_dir)
 logger = logging.getLogger("reload")
 logger.setLevel(logging.DEBUG)
 # create file handler which logs even debug messages
 fh = logging.FileHandler(self.logger_file)
 fh.setLevel(logging.DEBUG)
 # create formatter and add it to the handlers
 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
 fh.setFormatter(formatter)
 console = logging.StreamHandler()
 console.setLevel(logging.DEBUG)
 # add the handlers to the logger
 logger.addHandler(fh)
 logger.addHandler(console)
 return logger
def reloadIpset(self):
 """
 从文件中加载最新集合
 """
 reloadlog = mylog()
 try:
  # 刷新清空当前规则
  sub_call("/etc/init.d/iptables stop")
  sub_call("/etc/init.d/ipset restart")
  sub_call("/etc/init.d/iptables start")
  reloadlog.info("reload成功")
 except Exception as e:
  reloadlog.info("ipset reload异常 %s" % e)
def loadDefault(self):
 #self.addIps2Set('manage',self.getManageIps())
 self.addIps2Set('project',self.getProjectIps())

if __name__ == '__main__':
p = IpsetPool()
p.loadDefault()

来源:https://blog.csdn.net/u011085172/article/details/81193200

标签:python,ipset,白名单
0
投稿

猜你喜欢

  • python取余运算符知识点详解

    2023-05-16 00:04:50
  • 各种SQL语句速查手册

    2007-09-27 19:31:00
  • python 使用openpyxl读取excel数据

    2021-02-10 07:32:10
  • 解析JavaScript中 querySelector 与 getElementById 方法的区别

    2024-04-19 09:57:32
  • Python使用RSA库加密和解密

    2023-04-23 02:46:29
  • Python基础教程(一)——Windows搭建开发Python开发环境

    2021-06-16 13:41:53
  • asp实现*号隐藏IP地址

    2008-08-10 18:51:00
  • Windows10下mysql 8.0.19 安装配置方法图文教程

    2024-01-21 06:33:27
  • Python3的进程和线程你了解吗

    2023-05-19 00:33:30
  • 讲解Access数据库中数据表的自动重新联接

    2008-11-28 16:29:00
  • python字典嵌套字典的情况下找到某个key的value详解

    2021-12-07 12:04:37
  • em与px的区别以及em特点和应用

    2008-11-11 12:03:00
  • python批量解压zip文件的方法

    2022-08-26 16:20:00
  • MySQL中从库延迟状况排查的一则案例

    2024-01-21 01:32:53
  • Python JSON格式数据的提取和保存的实现

    2023-03-23 13:27:49
  • Python命名空间与作用域深入全面详解

    2022-03-07 08:36:10
  • python中用ctypes模拟点击的实例讲解

    2023-10-29 23:18:42
  • Python字典删除键值对和元素的四种方法(小结)

    2021-06-12 22:58:24
  • php获取域名的google收录示例

    2022-08-22 07:26:48
  • Python实现自动化域名批量解析分享

    2023-01-27 00:04:36
  • asp之家 网络编程 m.aspxhome.com