Skip to content

Instantly share code, notes, and snippets.

@qxj
Created May 23, 2012 14:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save qxj/2775611 to your computer and use it in GitHub Desktop.
Save qxj/2775611 to your computer and use it in GitHub Desktop.
Generate route files for openvpn in openwrt
#!/usr/bin/env python
"""
hacked for openwrt, from http://chnroutes.googlecode.com/files/chnroutes.py
"""
import re
import urllib2
import sys
import argparse
import math
def generate_openwrt():
results = fetch_ip_data()
upscript_header = """#!/bin/sh
export PATH="/bin:/sbin:/usr/sbin:/usr/bin"
OLDGW=`route -n|grep '^0\.0\.0\.0.*pppoe-wan$'|tr -s ' '|cut -d ' ' -f2`
if [ $OLDGW == '' ]; then
exit 0
fi
if [ ! -e /tmp/vpn_oldgw ]; then
echo $OLDGW > /tmp/vpn_oldgw
fi
"""
downscript_header = """#!/bin/sh
export PATH="/bin:/sbin:/usr/sbin:/usr/bin"
OLDGW=`cat /tmp/vpn_oldgw`
"""
upfile = open('vpnup','w')
downfile = open('vpndown','w')
upfile.write(upscript_header)
upfile.write('\n')
downfile.write(downscript_header)
downfile.write('\n')
for ip, mask, _ in results:
upfile.write('route add -net %s netmask %s gw $OLDGW\n'%(ip,mask))
downfile.write('route del -net %s netmask %s\n'%(ip,mask))
downfile.write('rm /tmp/vpn_oldgw\n')
print """Route files are generated.
Login to your openwrt, then copy vpnup to /etc/openvpn/vpnup, and copy vpndown to /etc/openvpn/vpndown.
Append following scripts into your openvpn.conf:
script-security 2
up /etc/openvpn/vpnup
down /etc/openvpn/vpndown
"""
def fetch_ip_data():
#fetch data from apnic
print "Fetching data from apnic.net, it might take a few minutes, please wait..."
url=r'http://ftp.apnic.net/apnic/stats/apnic/delegated-apnic-latest'
data=urllib2.urlopen(url).read()
cnregex=re.compile(r'apnic\|cn\|ipv4\|[0-9\.]+\|[0-9]+\|[0-9]+\|a.*',re.IGNORECASE)
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)
#convert to string
imask=hex(imask)[2:]
mask=[0]*4
mask[0]=imask[0:2]
mask[1]=imask[2:4]
mask[2]=imask[4:6]
mask[3]=imask[6:8]
#convert str to int
mask=[ int(i,16 ) for i in mask]
mask="%d.%d.%d.%d"%tuple(mask)
#mask in *nix format
mask2=32-int(math.log(num_ip,2))
results.append((starting_ip,mask,mask2))
return results
def main():
if len(sys.argv) > 1 and sys.argv[1] in ("-h", "--help"):
print "Run this script directly to generate route files for openvpn of openwrt."
sys.exit(1)
generate_openwrt()
if __name__=='__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment