背景:
小伙伴基于openresty写了一个管理iptables规则的web应用,web页面配置的IP地址最终会保存在服务器本地的一个文件中,内容示例:
[{"ip":"192.168.1.2"},{"ip":"192.168.1.3"},{"ip":"192.168.1.4"},{"ip":"192.168.1.2"},{"ip":"192.168.1.2"},{"ip":"192.168.1.2"},{"ip":"192.168.1.2"},{"ip":"192.168.1.2"}]
剩下的问题是如何把这些IP地址刷写到/etc/sysconfig/iptables中,考虑的解决方案是设置crontab,每分钟执行一次检查,有新内容则刷新规则;
于是写了个脚本,已经验证OK;
#!/bin/env python
#-*- coding: utf-8 -*-
#Author: Limuitech
#Date: 2018-11-12
#Version: 1.0
#Description:从ipConfFile获取ip地址列表---->构造防火墙规则---->替换掉/etc/sysconfig/iptables文件中#CONF-START和#CONF-END之间的规则;
import datetime
import os
import logging
import shutil
import commands
backupTime = datetime.datetime.now().strftime('%Y%m%d_%T')
#ipConfFile示例:
#[{"ip":"192.168.1.2"},{"ip":"192.168.1.3"},{"ip":"192.168.1.4"},{"ip":"192.168.1.2"},{"ip":"192.168.1.2"},{"ip":"192.168.1.2"},{"ip":"192.168.1.2"},{"ip":"192.168.1.2"}]
ipConfFile = '/root/ips.txt'
ipRulesFile = '/etc/sysconfig/iptables'
#备份iptables配置文件
def backup_etc_sysconfig_iptables():
bakDir = '/yourcorp/backup/iptables'
bakFile = 'iptables_' + backupTime
absFile = os.path.join(bakDir, bakFile)
if not os.path.exists(bakDir):
os.makedirs(bakDir, mode=0755)
shutil.copy('/etc/sysconfig/iptables', absFile)
#从openresty的web应用获取ip列表
def get_iplist(file):
#读取ip地址的配置文件,并生成列表
with open(file, 'r') as ips:
sData = ips.read()
oData = eval(sData)
return oData
#获取文件的md5值
def getFileMD5(filename):
cmd = "md5sum {0} | cut -d' ' -f1".format(filename)
fileMD5 = commands.getoutput(cmd)
return fileMD5
#添加规则
def set_rules(ipConfs):
newRules = ''
#构造添加的新规则内容,数据类型为字符串
for i in xrange(len(ipConfs)):
ipRule = '-A INPUT -s %s -j ACCEPT' % ipConfs[i]['ip'] + '\n'
newRules = newRules + ipRule
#拼接iptables文件的全部,并且写入到目标文件中,这里打开文件方式必须是rw
with open("/etc/sysconfig/iptables","rw") as nowConf:
content = nowConf.read()
content_add = newRules
startlen = len('#CONF-START')
startPos = content.find("#CONF-START") + startlen
endPos = content.find("#CONF-END")
content =content[:startPos] + '\n' + content_add + content[endPos:]
with open("/etc/sysconfig/iptables","w+") as nowConf_new:
nowConf_new.write(content)
if __name__ == '__main__':
if os.path.isfile("/tmp/iptables_md5"):
oldMD5 = commands.getoutput("cat /tmp/iptables_md5")
newMD5 = getFileMD5(ipConfFile)
if oldMD5 != newMD5:
with open("/tmp/iptables_md5", "w+") as imd:
imd.write(newMD5)
backup_etc_sysconfig_iptables()
iplist = get_iplist(ipConfFile)
set_rules(iplist)
commands.getoutput('/usr/sbin/service iptables reload')
else:
newMD5 = getFileMD5(ipConfFile)
with open("/tmp/iptables_md5", "w+") as imd:
imd.write(newMD5)
with open("/tmp/iptables_md5", "w+") as imd:
imd.write(newMD5)
backup_etc_sysconfig_iptables()
iplist = get_iplist(ipConfFile)
set_rules(iplist)
commands.getoutput('/usr/sbin/service iptables reload')