Skip to content

Commit 12f04a1

Browse files
committed
correct pep8 stype
1 parent 953402e commit 12f04a1

3 files changed

Lines changed: 99 additions & 69 deletions

File tree

‎ipblock.py‎

Lines changed: 26 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@
33
# Author: Andrey Skopenko <andrey@scopenco.net>
44
'''%prog [OPTIONS] <RULES_CONFIG>
55
6-
Anti DDOS tool used to block ip addresses in firewall based on access list of web server.
6+
Anti DDOS tool used to block ip addresses
7+
in firewall based on access list of web server.
78
89
Examples
910
$ python bin/ipblock.py etc/config -f access_log -d
@@ -19,12 +20,13 @@
1920
import logging.handlers
2021
import IPy
2122
import subprocess
22-
2323
from optparse import OptionParser, make_option
2424

25+
2526
def read_config(path):
2627

2728
drop_rules = []
29+
2830
def drop(pattern, mask):
2931
drop_rules.append((pattern, mask))
3032

@@ -42,29 +44,31 @@ def drop(pattern, mask):
4244
return data
4345
#end def read_config
4446

47+
4548
def open_anything(source):
4649
if source == "-":
4750
return sys.stdin
4851

49-
try:
52+
try:
5053
return open(source)
5154
except (OSError, IOError), e:
5255
logging.critical(e)
5356
sys.exit(1)
5457
#end def open_anything
5558

59+
5660
def setup_logging(appname, debug=False):
5761
""" set up logging """
5862

5963
log_dir = os.path.expanduser("~/.%s" % appname)
60-
if not os.access(log_dir,os.W_OK):
64+
if not os.access(log_dir, os.W_OK):
6165
try:
6266
os.makedirs(log_dir)
6367
except IOError, e:
64-
raise RuntimeError, "Could not create %d directory: " % log_dir, e
68+
raise RuntimeError("Could not create %d directory: " % log_dir), e
6569

66-
format='%(asctime)s: %(message)s'
67-
fileformat='%(asctime)s ipblock: %(message)s'
70+
format = '%(asctime)s: %(message)s'
71+
fileformat = '%(asctime)s ipblock: %(message)s'
6872
filename = os.path.join(log_dir, appname + ".log")
6973

7074
# common logging options
@@ -73,7 +77,8 @@ def setup_logging(appname, debug=False):
7377

7478
# file logging
7579
fileHandler = logging.handlers.RotatingFileHandler(filename,
76-
"a", maxBytes=1024*1024, backupCount=5)
80+
"a", maxBytes=1024*1024,
81+
backupCount=5)
7782
fileHandler.setFormatter(logging.Formatter(fileformat))
7883
rootLogger.addHandler(fileHandler)
7984

@@ -85,10 +90,13 @@ def setup_logging(appname, debug=False):
8590
rootLogger.addHandler(streamHandler)
8691
#end def setup_logging
8792

93+
8894
def main():
8995
option_list = [
90-
make_option('-f', '--file', dest='file', help='data file or pipe (-)'),
91-
make_option('-s', '--show', dest='show', action='count', help='Show only'),
96+
make_option('-f', '--file', dest='file',
97+
help='data file or pipe (-)'),
98+
make_option('-s', '--show', dest='show',
99+
action='count', help='Show only'),
92100
make_option('-d', '--debug', dest='debug', action='count',
93101
help='verbose output (use twice for extra debug)'),
94102
]
@@ -108,14 +116,14 @@ def main():
108116
# Config file overrides defaults
109117
config.update(read_config(config_file))
110118
# Options override config
111-
config.update(dict([ (k, v) for k, v in vars(options).items()
112-
if v is not None ]))
119+
config.update(dict([(k, v) for k, v in vars(options).items()
120+
if v is not None]))
113121

114122
# set logging
115123
debug = config.get('debug')
116124
setup_logging("ipblock", debug)
117125

118-
# start
126+
# start
119127
logging.info('run blocking')
120128
logging.debug('config: %r', config)
121129
logging.debug('options: %r', vars(options))
@@ -132,13 +140,13 @@ def main():
132140
for drop_rule, mask in drop_rules:
133141
# create regext cache
134142
logging.debug('compile drop rule: %r', drop_rule)
135-
regs.append((re.compile(drop_rule),mask))
143+
regs.append((re.compile(drop_rule), mask))
136144

137145
# compile pattern from config
138146
ip = re.compile(config.get('pattern'))
139147

140-
show_only = config.get('show');
141-
block_command = config.get('command');
148+
show_only = config.get('show')
149+
block_command = config.get('command')
142150

143151
nets = []
144152
for line in f:
@@ -151,9 +159,9 @@ def main():
151159
if show_only:
152160
print block_command % block_net
153161
else:
154-
logging.info('blocking %s' % block_net);
162+
logging.info('blocking %s' % block_net)
155163
subprocess.Popen(block_command % block_net, shell=True,
156-
stdout=subprocess.PIPE)
164+
stdout=subprocess.PIPE)
157165
break
158166

159167
if __name__ == '__main__':

‎netblock.py‎

Lines changed: 43 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
#!/usr/bin/env python
22
# -*- coding: UTF-8 -*-
33
# Author: Andrey Skopenko <andrey@scopenco.net>
4-
'''A tool create rules for Iptables that block or allow networks by country code
5-
(ex: RU CN etc.) For the correct execution of script need to download geip
4+
'''A tool create rules for Iptables that block
5+
or allow networks by country code(ex: RU CN etc.).
6+
For the correct execution of script need to download geip
67
database and country codes.'''
78

89
import csv
@@ -11,53 +12,60 @@
1112
import os.path
1213

1314
IPTABLES_BIN = '/sbin/iptables'
14-
MAXMIND_DB = 'http://www.maxmind.com/download/geoip/database/GeoIPCountryCSV.zip'
15+
MAXMIND_DB = \
16+
'http://www.maxmind.com/download/geoip/database/GeoIPCountryCSV.zip'
1517
COUTRY_DB = 'http://www.iso.org/iso/list-en1-semic-3.txt'
1618

19+
1720
def main():
1821
p = optparse.OptionParser(description=__doc__,
19-
prog="netblock",
20-
version="0.1",
21-
usage="%prog [-cc] [-c] [-i] [-p] [-d] [-a] country1 coutry2 ...")
22+
prog="netblock",
23+
version="0.1",
24+
usage="%prog [-cc] [-c] [-i] [-p]"
25+
"[-d] [-a] country1 coutry2 ...")
2226
p.add_option("--geoipdb",
23-
help='Path to GeoIPCountryWhois.csv with GeoIP data',
24-
default='GeoIPCountryWhois.csv')
27+
help='Path to GeoIPCountryWhois.csv with GeoIP data',
28+
default='GeoIPCountryWhois.csv')
2529
p.add_option("--countrydb",
26-
help='Path to country_names_and_code_elements_txt with country codes',
27-
default='country_names_and_code_elements_txt')
30+
help='Path to country_names_and_code_elements_txt '
31+
'with country codes',
32+
default='country_names_and_code_elements_txt')
2833
p.add_option("--cc",
29-
action='store_true',
30-
help='List of country codes')
34+
action='store_true',
35+
help='List of country codes')
3136
p.add_option("--chain", "-c",
32-
help='Iptables chain, default INPUT',
33-
default='INPUT')
37+
help='Iptables chain, default INPUT',
38+
default='INPUT')
3439
p.add_option("--interface", "-i",
35-
help='Iptables interface, default eth0',
36-
default='eth0')
40+
help='Iptables interface, default eth0',
41+
default='eth0')
3742
p.add_option("--protocol", "-p",
38-
help='Iptables protocol, choose from (icmp, tcp, udp, all)',
39-
action="store",
40-
type="choice",
41-
choices=["icmp", "tcp", "udp", 'all'])
43+
help='Iptables protocol, choose from (icmp, tcp, udp, all)',
44+
action="store",
45+
type="choice",
46+
choices=["icmp", "tcp", "udp", 'all'])
4247
p.add_option('--dport', '-d',
43-
help='Iptables destination port')
48+
help='Iptables destination port')
4449
p.add_option("--allow_only", "-a",
45-
help='Generate iptables rules that allow only selected coutry',
46-
action="store_true")
50+
help='Generate iptables rules that allow '
51+
'only selected coutry',
52+
action="store_true")
4753
options, arguments = p.parse_args()
4854

4955
# show list of country codes
5056
if options.cc:
5157
if not os.path.isfile(options.countrydb):
52-
print '%s not found! try command "wget %s"' % (options.countrydb, COUTRY_DB)
53-
sys.exit()
58+
print '%s not found! try command "wget %s"' % (
59+
options.countrydb, COUTRY_DB)
60+
sys.exit()
5461
with open(options.countrydb) as f:
5562
for line in f:
56-
if line == "" or line.startswith("Country ") or ";" not in line:
63+
if line == "" or line.startswith("Country ") \
64+
or ";" not in line:
5765
continue
5866
c_name, c_code = line.strip().split(";")
59-
c_name = ' '.join([part.capitalize() for part in \
60-
c_name.split(" ")])
67+
c_name = ' '.join([part.capitalize() for part in
68+
c_name.split(" ")])
6169
print '%s\t%s' % (c_code, c_name)
6270
return
6371

@@ -67,8 +75,10 @@ def main():
6775
sys.exit()
6876

6977
if not os.path.isfile(options.geoipdb):
70-
print '%s not found! try command "wget %s && unzip GeoIPCountryCSV.zip"' % (options.geoipdb, MAXMIND_DB)
71-
sys.exit()
78+
print '%s not found! try ' \
79+
'command "wget %s && unzip GeoIPCountryCSV.zip"' % (
80+
options.geoipdb, MAXMIND_DB)
81+
sys.exit()
7282

7383
# construct iptables rule tempate
7484
base_rule = IPTABLES_BIN
@@ -94,7 +104,8 @@ def main():
94104
while (network <= mask):
95105
x = 0
96106
while True:
97-
if network & (1 << x) == 0 and network + ((1 << (x + 1)) - 1) <= mask:
107+
if network & (1 << x) == 0 and \
108+
network + ((1 << (x + 1)) - 1) <= mask:
98109
x += 1
99110
continue
100111
print block_rule % '%s/%s' % (get_net(network), 32 - x)
@@ -104,6 +115,7 @@ def main():
104115
if options.allow_only:
105116
print base_rule + ' -j DROP'
106117

118+
107119
def get_net(network):
108120
'''convert bin network to decimal'''
109121
out = str(network & 255)

‎netnull.py‎

100755100644
Lines changed: 30 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -11,40 +11,46 @@
1111
import os.path
1212

1313
ROUTE_BIN = 'ip route'
14-
MAXMIND_DB = 'http://www.maxmind.com/download/geoip/database/GeoIPCountryCSV.zip'
14+
MAXMIND_DB = \
15+
'http://www.maxmind.com/download/geoip/database/GeoIPCountryCSV.zip'
1516
COUTRY_DB = 'http://www.iso.org/iso/list-en1-semic-3.txt'
1617

18+
1719
def main():
1820
p = optparse.OptionParser(description=__doc__,
19-
prog="netblock",
20-
version="0.1",
21-
usage="%prog [-cc] [-c] [-i] [-p] [-d] [-a] country1 coutry2 ...")
21+
prog="netblock",
22+
version="0.1",
23+
usage="%prog [-cc] [-c] [-i] [-p] "
24+
"[-d] [-a] country1 coutry2 ...")
2225
p.add_option("--geoipdb",
23-
help='Path to GeoIPCountryWhois.csv with GeoIP data',
24-
default='GeoIPCountryWhois.csv')
26+
help='Path to GeoIPCountryWhois.csv with GeoIP data',
27+
default='GeoIPCountryWhois.csv')
2528
p.add_option("--countrydb",
26-
help='Path to country_names_and_code_elements_txt with country codes',
27-
default='country_names_and_code_elements_txt')
29+
help='Path to country_names_and_code_elements_txt '
30+
'with country codes',
31+
default='country_names_and_code_elements_txt')
2832
p.add_option("--cc",
29-
action='store_true',
30-
help='List of country codes')
33+
action='store_true',
34+
help='List of country codes')
3135
p.add_option("--remove_nullroute", "-r",
32-
help='Generate rules to remove subnets from ip route table',
33-
action="store_true")
36+
help='Generate rules to remove subnets from ip route table',
37+
action="store_true")
3438
options, arguments = p.parse_args()
3539

3640
# show list of country codes
3741
if options.cc:
3842
if not os.path.isfile(options.countrydb):
39-
print '%s not found! try command "wget %s"' % (options.countrydb, COUTRY_DB)
40-
sys.exit()
43+
print '%s not found! try command "wget %s"' % (
44+
options.countrydb, COUTRY_DB)
45+
sys.exit()
4146
with open(options.countrydb) as f:
4247
for line in f:
43-
if line == "" or line.startswith("Country ") or ";" not in line:
48+
if line == "" or line.startswith("Country ") or \
49+
";" not in line:
4450
continue
4551
c_name, c_code = line.strip().split(";")
46-
c_name = ' '.join([part.capitalize() for part in \
47-
c_name.split(" ")])
52+
c_name = ' '.join([part.capitalize() for part in
53+
c_name.split(" ")])
4854
print '%s\t%s' % (c_code, c_name)
4955
return
5056

@@ -54,8 +60,10 @@ def main():
5460
sys.exit()
5561

5662
if not os.path.isfile(options.geoipdb):
57-
print '%s not found! try command "wget %s && unzip GeoIPCountryCSV.zip"' % (options.geoipdb, MAXMIND_DB)
58-
sys.exit()
63+
print '%s not found! try ' \
64+
'command "wget %s && unzip GeoIPCountryCSV.zip"' % (
65+
options.geoipdb, MAXMIND_DB)
66+
sys.exit()
5967

6068
# construct route rule tempate
6169
base_rule = ROUTE_BIN
@@ -73,13 +81,15 @@ def main():
7381
while (network <= mask):
7482
x = 0
7583
while True:
76-
if network & (1 << x) == 0 and network + ((1 << (x + 1)) - 1) <= mask:
84+
if network & (1 << x) == 0 and \
85+
network + ((1 << (x + 1)) - 1) <= mask:
7786
x += 1
7887
continue
7988
print block_rule % '%s/%s' % (get_net(network), 32 - x)
8089
break
8190
network += 1 << x
8291

92+
8393
def get_net(network):
8494
'''convert bin network to decimal'''
8595
out = str(network & 255)

0 commit comments

Comments
 (0)