-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathiptables_manager.py
60 lines (42 loc) · 1.42 KB
/
iptables_manager.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
__author__ = 'romanl'
import subprocess
import pymongo
conn = pymongo.Connection()
db = conn.iptables
blacklist = db.blacklist
whitelist = db.whitelist
class IpTablesManager(object):
def add_ips_to_block_list(self, ips):
counter = 0
for ip in ips:
exists = blacklist.find_one({'IP': ip})
if not exists:
subprocess.call('iptables -I INPUT -s {0} -j DROP'.format(ip), shell=True)
blacklist.insert({'IP': ip})
counter += 1
print 'Added {0} Rules to table'.format(counter)
def remove_ips_from_block_list(self, ips):
for ip in ips:
subprocess.call('iptables -D INPUT -s {0} -j DROP'.format(ip))
blacklist.remove({'IP': ip})
def get_blacklist(self):
return blacklist.find()
def get_whitelist(self):
return whitelist.find()
def add_to_whitelist(self, ips):
for ip in ips:
exists = blacklist.find_one({'IP': ip})
if not exists:
whitelist.insert({'IP': ip})
def remove_from_whitelist(self, ips):
for ip in ips:
whitelist.remove({'IP': ip})
def flush(self, with_db=True):
subprocess.call('iptables -t filter -F ', shell=True)
if with_db:
blacklist.remove()
whitelist.remove()
def main(*args, **kwargs):
mgr = IpTablesManager()
if __name__ == '__main__':
main()