python ipset管理 增删白名单的方法
为方便用ipset来管理防火墙,写了下面Ipset类来对Ip进行管理
#!/usr/bin/envpython #coding:utf-8 importMySQLdb importMySQLdb.cursors importsubprocess importlogging importre,os importxml.sax classXMLHandler(xml.sax.ContentHandler): ''' 用来解析ipset数据 ''' def__init__(self): self.current_tag="" self.current_set="" self.mapping={} defstartElement(self,name,attributes): self.current_tag=name ifname=='ipset': self.current_set=attributes['name'] self.mapping[self.current_set]=[] defcharacters(self,data): ifself.current_tag=='elem'anddata!='\n': self.mapping[self.current_set].append(data) defendElement(self,name): ifname=='ipset': self.current_set='' defgetData(self): returnself.mapping classIpsetPool(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) defsub_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)ifretcode!=0else(True,outdata)) returnretcode,outdata,errdata @staticmethod defquerydb(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() returnrs defgetManageIps(self): sql="select*fromhostwherestatenotin(6)and`use`REGEXP',2$|^2,|^2$|,2,';" return[x["ip1"]forxinself.querydb(sql)] defgetProjectIps(self): fromjgconf.modelsimportprojectConf return[i['saltIp']foriteminprojectConf.objects.all()foriinitem.getSaltServer()] defcheckAddrIsIn(self,ip,setname): ''' 判断ip是否在某个set中 ''' ifipinself.ipset_data[setname]: returnTrue else: returnFalse defgetIpsetData(self,xml_handler): ''' 获取机器上当前的ipset配置数据 ''' xh=xml_handler() xml.sax.parseString(self.sub_call('ipsetlist-oxml')[1],xh) returnxh.getData() defcreateSet(self,setname): self.log.info('create{0}set'.format(setname)) set_cmd='ipsetcreate{0}hash:ip'.format(setname) returnself.sub_call(set_cmd) defrenderSetFile(self): ''' 重导配置 ''' self.sub_call('ipsetsave>{0}'.format(self.config)) defcreateIpsets(self): foripsetinself.ipsets: self.createSet(ipset) defaddIps2Set(self,setname,ips): ifsetnamenotinself.ipsets: self.log.error('invalidsetname!') returnFalse ifnotself.ipset_data.has_key(setname): self.createSet(setname) foripinips: ifnotself.checkAddrIsIn(ip,setname): self.log.info('add{0}{1}'.format(setname,ip)) self.sub_call('ipset-A{0}{1}'.format(setname,ip)) self.renderSetFile() defdelIpsFromSet(self,setname,ips): self.log.info(ips) ifsetnameinself.ipsetsandself.ipset_data.has_key(setname): foripinips: ifself.checkAddrIsIn(ip,setname): self.log.info('delete{0}{1}'.format(setname,ip)) self.sub_call('ipset-D{0}{1}'.format(setname,ip)) self.renderSetFile() defmylog(self): logger_dir=os.path.split(self.logger_file)[0] ifnotos.path.exists(logger_dir): os.makedirs(logger_dir) logger=logging.getLogger("reload") logger.setLevel(logging.DEBUG) #createfilehandlerwhichlogsevendebugmessages fh=logging.FileHandler(self.logger_file) fh.setLevel(logging.DEBUG) #createformatterandaddittothehandlers formatter=logging.Formatter('%(asctime)s-%(name)s-%(levelname)s-%(message)s') fh.setFormatter(formatter) console=logging.StreamHandler() console.setLevel(logging.DEBUG) #addthehandlerstothelogger logger.addHandler(fh) logger.addHandler(console) returnlogger defreloadIpset(self): """ 从文件中加载最新集合 """ reloadlog=mylog() try: #刷新清空当前规则 sub_call("/etc/init.d/iptablesstop") sub_call("/etc/init.d/ipsetrestart") sub_call("/etc/init.d/iptablesstart") reloadlog.info("reload成功") exceptExceptionase: reloadlog.info("ipsetreload异常%s"%e) defloadDefault(self): #self.addIps2Set('manage',self.getManageIps()) self.addIps2Set('project',self.getProjectIps()) if__name__=='__main__': p=IpsetPool() p.loadDefault()
以上这篇pythonipset管理增删白名单的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。