forked from jimmyxu/chnroutes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chnroutes.py
executable file
·246 lines (179 loc) · 5.7 KB
/
chnroutes.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
#!/usr/bin/env python
import argparse
import math
import os
import re
import subprocess
import sys
import urllib2
def generate_ovpn(_):
results = fetch_ip_data()
upscript_header = """\
#!/bin/bash -
export PATH="/bin:/sbin:/usr/sbin:/usr/bin"
OLDGW=$(ip route show 0/0 | sed -e 's/^default//')
ip -batch - <<EOF
"""
downscript_header = """\
#!/bin/bash -
export PATH="/bin:/sbin:/usr/sbin:/usr/bin"
ip -batch - <<EOF
"""
upfile = open('vpn-up.sh', 'w')
downfile = open('vpn-down.sh', 'w')
upfile.write(upscript_header)
downfile.write(downscript_header)
for ip, _, mask in results:
upfile.write('route add %s/%s $OLDGW\n' % (ip, mask))
downfile.write('route del %s/%s\n' % (ip, mask))
upfile.write('EOF\n')
downfile.write('EOF\n')
upfile.close()
downfile.close()
os.chmod('vpn-up.sh', 00755)
os.chmod('vpn-down.sh', 00755)
def generate_old(metric):
results = fetch_ip_data()
rfile = open('routes.txt','w')
rfile.write('max-routes %d\n\n' % (len(results) + 20))
for ip, mask, _ in results:
rfile.write("route %s %s net_gateway %d\n" % (ip, mask, metric))
rfile.close()
def generate_linux(metric):
results = fetch_ip_data()
upscript_header = """\
#!/bin/bash -
OLDGW=$(ip route show 0/0 | head -n1 | grep 'via' | grep -Po '\d+\.\d+\.\d+\.\d+')
if [ $OLDGW == '' ]; then
exit 0
fi
if [ ! -e /tmp/vpn_oldgw ]; then
echo $OLDGW > /tmp/vpn_oldgw
fi
ip -batch - <<EOF
"""
downscript_header = """\
#!/bin/bash
export PATH="/bin:/sbin:/usr/sbin:/usr/bin"
OLDGW=$(cat /tmp/vpn_oldgw)
ip -batch - <<EOF
"""
upfile = open('ip-pre-up', 'w')
downfile = open('ip-down', 'w')
upfile.write(upscript_header)
downfile.write(downscript_header)
for ip, _, mask in results:
upfile.write('route add %s/%s via $OLDGW metric %s\n' %
(ip, mask, metric))
downfile.write('route del %s/%s\n' % (ip, mask))
upfile.write('EOF\n')
downfile.write('''\
EOF
rm /tmp/vpn_oldgw
''')
upfile.close()
downfile.close()
os.chmod('ip-pre-up', 00755)
os.chmod('ip-down', 00755)
def generate_mac(_):
results = fetch_ip_data()
upscript_header = """\
#!/bin/sh
export PATH="/bin:/sbin:/usr/sbin:/usr/bin"
OLDGW=`netstat -nr | grep '^default' | grep -v 'ppp' | sed 's/default *\\([0-9\.]*\\) .*/\\1/'`
if [ ! -e /tmp/pptp_oldgw ]; then
echo "${OLDGW}" > /tmp/pptp_oldgw
fi
dscacheutil -flushcache
"""
downscript_header = """\
#!/bin/sh
export PATH="/bin:/sbin:/usr/sbin:/usr/bin"
if [ ! -e /tmp/pptp_oldgw ]; then
exit 0
fi
OLDGW=`cat /tmp/pptp_oldgw`
"""
upfile = open('ip-up','w')
downfile = open('ip-down','w')
upfile.write(upscript_header)
downfile.write(downscript_header)
for ip, _, mask in results:
upfile.write('route add %s/%s "${OLDGW}"\n' % (ip, mask))
downfile.write('route delete %s/%s ${OLDGW}\n' % (ip, mask))
downfile.write('\n\nrm /tmp/pptp_oldgw\n')
upfile.close()
downfile.close()
os.chmod('ip-up', 00755)
os.chmod('ip-down', 00755)
def generate_win(metric):
results = fetch_ip_data()
upscript_header = """\
@echo off
for /F "tokens=3" %%* in ('route print ^| findstr "\\<0.0.0.0\\>"') do set "gw=%%*"
"""
upfile = open('vpnup.bat','w')
downfile = open('vpndown.bat','w')
upfile.write(upscript_header)
upfile.write('ipconfig /flushdns\n\n')
downfile.write("@echo off")
downfile.write('\n')
for ip, mask, _ in results:
upfile.write('route add %s mask %s %s metric %d\n' %
(ip, mask, "%gw%", metric))
downfile.write('route delete %s\n' % ip)
upfile.close()
downfile.close()
def fetch_ip_data():
url = 'http://ftp.apnic.net/apnic/stats/apnic/delegated-apnic-latest'
try:
data = subprocess.check_output(['wget', url, '-O-'])
except (OSError, AttributeError):
print >> sys.stderr, "Fetching data from apnic.net, "\
"it might take a few minutes, please wait..."
data = urllib2.urlopen(url).read()
cnregex = re.compile(r'^apnic\|cn\|ipv4\|[\d\.]+\|\d+\|\d+\|a\w*$',
re.I | re.M)
cndata = cnregex.findall(data)
results = []
for item in cndata:
unit_items = item.split('|')
starting_ip = unit_items[3]
num_ip = int(unit_items[4])
imask = 0xffffffff ^ (num_ip - 1)
imask = hex(imask)[2:]
mask = [imask[i:i + 2] for i in xrange(0, 8, 2)]
mask = '.'.join([str(int(i, 16)) for i in mask])
cidr = 32 - int(math.log(num_ip, 2))
results.append((starting_ip, mask, cidr))
return results
def main():
parser = argparse.ArgumentParser(
description="Generate routing rules for VPN users in China.")
parser.add_argument('-p',
dest='platform',
default='openvpn',
nargs='?',
choices=['openvpn', 'old', 'mac', 'linux', 'win'],
help="target platform")
parser.add_argument('-m',
dest='metric',
default=5,
nargs='?',
type=int,
help="metric")
args = parser.parse_args()
if args.platform.lower() == 'openvpn':
generate_ovpn(args.metric)
elif args.platform.lower() == 'old':
generate_old(args.metric)
elif args.platform.lower() == 'linux':
generate_linux(args.metric)
elif args.platform.lower() == 'mac':
generate_mac(args.metric)
elif args.platform.lower() == 'win':
generate_win(args.metric)
else:
exit(1)
if __name__ == '__main__':
main()