我正在学习Python,并使用python-iptables库编写了一些设置iptables的代码。我遇到的问题是,我不得不反复重写很多相同的代码行。我有点了解函数,但并不懂面向对象编程。我认为有更好的面向对象编程方式来编写这段代码,但我无法理解它。任何指针将不胜感激。以下是代码。
import iptc
def dropAllInbound():
chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), 'INPUT')
rule = iptc.Rule()
rule.in_interface = 'eth+'
rule.target = iptc.Target(rule, 'DROP')
chain.insert_rule(rule)
def allowLoopback():
chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), 'INPUT')
rule = iptc.Rule()
rule.in_interface = 'lo'
rule.target = iptc.Target(rule, 'ACCEPT')
chain.insert_rule(rule)
def allowEstablishedInbound():
chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), 'INPUT')
rule = iptc.Rule()
match = rule.create_match('state')
match.state = 'RELATED,ESTABLISHED'
rule.target = iptc.Target(rule, 'ACCEPT')
chain.insert_rule(rule)
def allowHTTP():
chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), 'INPUT')
rule = iptc.Rule()
rule.in_interface = 'eth+'
rule.protocol = 'tcp'
match = rule.create_match('tcp')
match.dport = '80'
rule.target = iptc.Target(rule, 'ACCEPT')
chain.insert_rule(rule)
def allowHTTPS():
chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), 'INPUT')
rule = iptc.Rule()
rule.in_interface = 'eth+'
rule.protocol = 'tcp'
match = rule.create_match('tcp')
match.dport = '443'
rule.target = iptc.Target(rule, 'ACCEPT')
chain.insert_rule(rule)
def allowSSH():
chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), 'INPUT')
rule = iptc.Rule()
rule.in_interface = 'eth+'
rule.protocol = 'tcp'
match = rule.create_match('tcp')
match.dport = '22'
rule.target = iptc.Target(rule, 'ACCEPT')
chain.insert_rule(rule)
def allowEstablishedOutbound():
chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), 'OUTPUT')
rule = iptc.Rule()
match = rule.create_match('state')
match.state = 'RELATED,ESTABLISHED'
rule.target = iptc.Target(rule, 'ACCEPT')
chain.insert_rule(rule)
def dropAllOutbound():
chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), 'OUTPUT')
rule = iptc.Rule()
rule.in_interface = 'eth+'
rule.target = iptc.Target(rule, 'DROP')
chain.insert_rule(rule)
def defaultAction():
dropAllOutbound()
dropAllInbound()
allowLoopback()
allowEstablishedInbound()
allowEstablishedOutbound()
def getInput():
print 'Default action (1) is most secure '
print 'Default - 1'
print 'HTTP - 2'
print 'HTTPS - 3'
print 'SSH - 4'
print 'Exit - 5'
choices = raw_input('Enter choices (comma Separated) ').split(',')
for action in choices:
if action == "1":
defaultAction()
break
if action == "2":
allowHTTP()
break
if action == "3":
allowHTTPS()
break
if action == "4":
allowSSH()
break
else:
break
getInput()
注意所有规则都有相似的代码行。是否有一种方法可以创建一个规则生成器对象或类似的东西来最小化重复编写代码的工作?
我添加了以下函数,并在每次运行脚本时调用它,以便清除规则。
def startClean():
chainIn = iptc.Chain(iptc.Table(iptc.Table.FILTER), 'INPUT')
chainIn.flush()
chainOut = iptc.Chain(iptc.Table(iptc.Table.FILTER), 'OUTPUT')
chainOut.flush()