@@ -64,7 +64,7 @@ def __init__(self, host, chain_name):
6464
6565 def edit_chain (
6666 self , action , chain_name , address_type , dest , target , protocol = 'all' ,
67- ports = None
67+ ports = None , rule_num = None
6868 ):
6969 """
7070 Changes firewall configuration
@@ -79,6 +79,8 @@ def edit_chain(
7979 target (str): target rule to apply
8080 protocol (str): affected network protocol, Default is 'all'
8181 ports (list): list of ports to configure
82+ rule_num (str): the number given after the chain name indicates the
83+ position where the rule will be inserted
8284
8385 Returns:
8486 bool: True if configuration change succeeded, False otherwise
@@ -89,16 +91,28 @@ def edit_chain(
8991
9092 Example:
9193 edit_chain(
92- action='--append',chain='OUTPUT', address_type='--destination',
93- dest={'address': nfs_server}, target='DROP'
94+ action='--append',chain='OUTPUT',
95+ rule_num='1',
96+ address_type='--destination',
97+ dest={'address': nfs_server},
98+ target='DROP'
9499 )
95100 """
96- dest = "," .join (dest ['address' ])
97101 cmd = [
98- self .firewall_service , action , chain_name , address_type , dest ,
99- '--jump' , target .upper (), '--protocol' , protocol
102+ self .firewall_service , action , chain_name
100103 ]
101104
105+ if rule_num :
106+ cmd .extend ([rule_num ])
107+
108+ dest = "," .join (dest ['address' ])
109+ cmd .extend (
110+ [
111+ address_type , dest , '--jump' , target .upper (),
112+ '--protocol' , protocol
113+ ]
114+ )
115+
102116 if ports :
103117 # Iptables multiport module accepts up to 15 ports
104118 if len (ports ) > 15 :
@@ -144,6 +158,29 @@ def add_rule(self, dest, target, protocol='all', ports=None):
144158 protocol , ports
145159 )
146160
161+ def insert_rule (self , dest , target , protocol = 'all' , ports = None ,
162+ rule_num = None ):
163+ """
164+ Insert new firewall rule to a specific chain
165+
166+ Args:
167+ dest (dict): 'address' key and value containing destination host or
168+ list of destination hosts
169+ target (str): Target rule to apply
170+ protocol (str): affected network protocol, Default is 'all'
171+ ports (list): list of ports to configure
172+ rule_num (str): the number given after the chain name indicates
173+ the position where the rule will be inserted. If the rule_num is
174+ not given , the new rule is inserted in the line 1.
175+
176+ Returns:
177+ bool: False if inserting new rule failed, True if it succeeded
178+ """
179+ return self .edit_chain (
180+ '--insert' , self .chain_name , self .address_type , dest , target ,
181+ protocol , ports , rule_num
182+ )
183+
147184 def delete_rule (self , dest , target , protocol = 'all' , ports = None ):
148185 """
149186 Delete existing firewall rule from a specific chain
0 commit comments