Python chnroutes Ros Edition

Source: Internet
Author: User
Tags routeros

Chnroutes estimated that many people know the network. It's pretty good. Automatically update the routing table script.

Squeeze a little bit of time to simply revise it a bit. It supports the generation of RouterOS scripts, which makes it easy for the soft router to do the IP auto-select line.
Note that the script clears the original address list china_address_lists

#!/usr/bin/env pythonimport reimport urllib2import sysimport argparseimport mathimport textwrapimport timedef generate_ Ros (Metric): results = Fetch_ip_data () rosscript_header=textwrap.dedent ("" "#%s by chnrouters #/IP Firewa ll address-list remove [Find list =china_address_lists] "" "% time.strftime ('%b/%d/%y%h:%m:%s ', Time.localtime (        Time.time ())) Rfile=open (' ROS_ADDLIST_CHINA.RSC ', ' W ') Rfile.write (Rosscript_header) for Ip,_,mask2 in results: address_item= "Add address=%s/%d list=china_address_lists\n"% (ip,mask2) rfile.write (Address_item) Rfile.clo SE () print "usage:import The content of the newly created ROS_ADDLIST_CHINA.RSC to your RouterOS," "Script W Hile clear the original before Add. "        def GENERATE_OVPN (metric): results = Fetch_ip_data () rfile=open (' Routes.txt ', ' W ') for ip,mask,_ in results:   Route_item= "route%s%s Net_gateway%d\n"% (ip,mask,metric) rfile.write (Route_item) rfile.close () Print "Usage:append The content of the newly created routes.txt to your OpenVPN config file," "and also add" Max-routes%d ', which takes a line, to the head of the file. "% (len (results) +20) def generate_linux (metric): results =        Fetch_ip_data () upscript_header=textwrap.dedent ("" "#!/bin/bash export path="/bin:/sbin:/usr/sbin:/usr/bin " Oldgw= ' IP route Show | grep ' ^default ' | Sed-e ' S/default via \ \ ([^]*\\). */\\1/' if [$OLDGW = = ']; Then Exit 0 fi if [!-E/TMP/VPN_OLDGW];    Then echo $OLDGW >/tmp/vpn_oldgw fi "" ") Downscript_header=textwrap.dedent (" "" #!/bin/bash Export path= "/bin:/sbin:/usr/sbin:/usr/bin" oldgw= ' CAT/TMP/VPN_OLDGW ' "") Upfile=open (' ip-pre-up ', ' W ') downfile=open (' Ip-down ', ' W ') Upfile.write (upscript_header) upfile.write (' \ n ') Downfile.write (downsc Ript_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)) Dow           Nfile.write (' rm/tmp/vpn_oldgw\n ') print "For PPTP only, please copy the file ip-pre-up to the FOLDER/ETC/PPP," "and copy the file Ip-down to the FOLDER/ETC/PPP/IP-DOWN.D." def GENERATE_MAC (Metric): Results=fetch_ip_data () upscript_header=textwrap.dedent ("" "#!/bin/sh export PAT H= "/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 =textwrap.dedent ("" "#!/bin/sh export path="/bin:/sbin:/usr/sbin:/usr/bin "if [! -E/TMP/PPTP_OLDGW]; Then Exit 0 fi odlgw= ' CAT/TMP/PPTP_OLDGW ' "" ") Upfile=open (' ip-up ', ' W ') Downfile=op En (' Ip-down ', ' W ') Upfile.write (upScript_header) upfile.write (' \ n ') downfile.write (downscript_header) downfile.write (' \ n ') 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 () print "for PP TP on Mac only, please copy ip-up and Ip-down to The/etc/ppp folder, "" Don t forget to make them executable wit H the chmod command. " def generate_win (metric): results = Fetch_ip_data () upscript_header=textwrap.dedent ("" "@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 (' \ n ') 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 () # up_vbs_wrapper=open (' Vpnup.vbs ', ' W ') # up_vbs_wrapper.write (' Set Objshell = C Reateobject ("Wscript.Shell") \ncall objshell.run ("Vpnup.bat", 0,false) ') # Up_vbs_wrapper.close () # down_vbs_wrapper= Open (' Vpndown.vbs ', ' W ') # down_vbs_wrapper.write (' Set Objshell = CreateObject ("Wscript.Shell") \ncall Objshell.run (" Vpndown.bat ", 0,false) ') # Down_vbs_wrapper.close () print" For PPTP on Windows only, run Vpnup.bat before dialing To VPN, "and run Vpndown.bat after disconnected from the VPN." def generate_android (metric): results = Fetch_ip_data () upscript_header=textwrap.dedent ("" "#!/bin/sh Alia    S nestat= '/system/xbin/busybox netstat ' alias grep= '/system/xbin/busybox grep ' Alias awk= '/system/xbin/busybox awk ' Alias Route= '/system/xbin/busybox route ' oldgw= ' netstat-rn | grep ^0\.0\.0\.0 | awk ' {print $} ' "" "Downscript_header=textwrap.dedent (" "" #!/bin/sh alias Route= '/system/xbin/busyb Ox route ' "") upfile=open (' vpnup.sh ', ' W ') downfile=open (' vpndown.sh ', ' W ') Upfile.write (upscript_h         Eader) 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 Netmas K%s\n '% (ip,mask)) Upfile.close () downfile.close () print "old school-to-call Up/down script from Open VPN client. "Use the regular OpenVPN 2.1 method to add routes if it's possible" Def Fetch_ip_data (): #fetch data from AP NIC print "Fetching data from apnic.net, it might take a few minutes, please wait ..." url=r "HTTP://FTP.APNIC.NET/APN Ic/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] m ask= "%d.%d.%d.%d"%tuple (mask) #mask in *nix format mask2=32-int (Math.log (num_ip,2)) r Esults.append ((STARTING_IP,MASK,MASK2)) return resultsif __name__== ' __main__ ': Parser=argparse.    Argumentparser (description= "Generate routing rules for VPN.")                        Parser.add_argument ('-P ', '--platform ', dest= ' platform ', default= ' RouterOS ', Nargs= '? ', help= "TArget platforms, it can be OpenVPN, Mac, Linux, "" Win, Android.    OpenVPN by default. ")                        Parser.add_argument ('-M ', '--metric ', dest= ' metric ', default=5,        Nargs= '? ', Type=int, help= "Metric setting for the route Rules") args = Parser.parse_args () if args.platform.lower () = = ' OpenVPN ': Generate_ovpn (args.metric) elif ar Gs.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) elif args.platform.lower () = = ' Android ': Generate_android (args.metric) elif args.platform.lower () = = ' RouterOS ': Generate_ros (args.me tric) Else:print>>sys.stderr, "Platform%s is not supported." %args.platform exit (1)

  

Python chnroutes Ros Edition

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.