像Win7 之类的系统,一旦开启VPN后,所有流量都通过VPN出去了,但这往往是没有必要的,我们只希望国外的网址最好是被墙的网址走VPN,其他正常走网关。

那么问题来了,如何才能判断是国外的或者国内的网址呢,其实很简单,通过亚太互联网络信息中心 (Asia-Pacific Network Information Centre,APNIC)网站获取分配给CN的ip段即可,对于CN网段的IPV4地址走默认网关。
这样就可以在不使用openwrt等路由器的情况下,动态选择路由(即访问国内网站直连,访问国外网站用vpn)了,非常节省。。。。

下面是动态路由的perl脚本,适用于win7
如果要删除路由,只需在同文件夹下建一个deleteip.txt的空文件即可

#!/usr/bin/perl -w

use strict;

use warnings;

$| =1;
use LWP;
use LWP::Simple;
use LWP::UserAgent;
use HTTP::Cookies;
use HTTP::Headers;
use HTTP::Response;

my $ua = LWP::UserAgent->new;
$ua->agent("Mozilla/5.0 (Windows NT 6.1; rv:30.0) Gecko/20100101 Firefox/30.0");
my $cookie_jar = HTTP::Cookies->new(file=>'lwp_cookies.txt',autosave=>1, ignore_discard=>1);
$ua->cookie_jar($cookie_jar); 
my $page='';
my $delsig=0;
if(-e "deleteip.txt")
{
   $delsig=1;
}

if(!-e "ip.list"){
my $result = $ua->get("http://ftp.apnic.net/apnic/stats/apnic/delegated-apnic-latest");
die"An error occurred:", $result->status_line() unless $result->is_success;

$page=$result->content;;

open(IPFILE,">ip.list") or die "file ip.list cannot be created";
print IPFILE $page;
close(IPFILE);
}else
{
open(IPFILE2,"<ip.list") or die "file ip.list cannot be opened";
while(my $content = <IPFILE2>)
{
	$page =$page.$content;
	}
close(IPFILE2);
}
my @line = split("\n",$page);

my $route = `route print 0*`;

$route =~ s/\n//g;
my $gatewayip='';
if($route =~/0\.0\.0\.0\s+0\.0\.0\.0\s+(\d+\.\d+\.\d+\.\d+)/)
{$gatewayip=$1;print "################$gatewayip##############";}

my $i=0;

foreach my $cc (@line)
{
    chomp $cc;
    if(!$cc=~/^apnic/){next;}
    #print $cc,"\n";
    my @el = split /\|/,$cc;
     my $locate =$el[1];
 
     my $iptype =$el[2];
     my $ip = $el[3];
         #print $locate,' ',$ip,' ',$iptype,"\n";
     if(defined $locate and $locate eq 'CN' and $iptype eq 'ipv4'){
     	
     	my $mask = int (32- log($el[4])/log(2));
    
   
     $i++;
    if($delsig==0) {print "route -p add $ip/$mask $gatewayip metric 25\n"; system("route -p add $ip/$mask $gatewayip metric 25");}
    else{print "route delete $ip\n";system("route delete $ip");}
   }
  
  
    #system("route add $line mask------------- 255.255.255.0 $ip metric 25");
}
print $i;