欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-04-07 22:42:49
为方便用ipset 来管理防火墙,写了下面ipset类来对ip进行管理 #!/usr/bin/env python # coding: utf-8 im...

为方便用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()

以上这篇python ipset管理 增删白名单的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。