91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

python ipset管理 增刪白名單的方法

發布時間:2020-09-08 23:50:01 來源:腳本之家 閱讀:161 作者:云中不知人 欄目:開發技術

為方便用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管理 增刪白名單的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持億速云。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

兰坪| 澎湖县| 丰台区| 旬阳县| 芜湖市| 呼和浩特市| 赣州市| 平谷区| 饶平县| 梨树县| 湾仔区| 从化市| 永清县| 井冈山市| 汉寿县| 大丰市| 防城港市| 扎囊县| 乐亭县| 龙游县| 蓝山县| 武隆县| 陆良县| 新宾| 台南县| 吉林市| 登封市| 泸溪县| 昌乐县| 普安县| 宣恩县| 福鼎市| 潜江市| 扬州市| 商洛市| 常宁市| 青州市| 阿克陶县| 潞西市| 茌平县| 萨嘎县|