Skip to content

Instantly share code, notes, and snippets.

@ergatea
Last active December 11, 2015 02:39
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 ergatea/4532567 to your computer and use it in GitHub Desktop.
Save ergatea/4532567 to your computer and use it in GitHub Desktop.
debian route 更新脚本
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
import urllib
import math
import subprocess
def external_cmd(cmd):
try:
proc = subprocess.Popen(cmd, shell=True,
stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,)
stdout_value, stderr_value = proc.communicate()
return stdout_value, stderr_value
except ValueError as error:
return None, error
except IOError as error:
return None, error
def fetch_ip_data():
#fetch data from apnic
print "Fetching data from apnic.net, it might take a few minutes, please wait..."
apnic='http://ftp.apnic.net/apnic/stats/apnic/delegated-apnic-latest'
source=urllib.urlopen(apnic).read()
regex=re.compile(r'apnic\|cn\|ipv4\|[0-9\.]+\|[0-9]+\|[0-9]+\|a.*',re.IGNORECASE)
data=regex.findall(source)
results=[]
for item in data:
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
if __name__=='__main__':
results = fetch_ip_data()
gateway, error = external_cmd(["ip route show | grep '^default' | sed -e 's/default via \\([^ ]*\\).*/\\1/'"])
for ip,mask,_ in results:
output, error = external_cmd(['/sbin/route add -net %s netmask %s gw %s'%(ip,mask,gateway)])
print "%s/%s"%(output, error)
print "Processing is complete!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment