选择网速最快的vpn进行连接的脚本

下午github上下载速度只有几K,用了代理也不到10K,后来发现所用的vpn服务器选择了一个慢的。写了这段脚本,用来从可用的vpn选出最快的那个。脚本只适用于mac,并且前提是你已创建好了所有可选的vpn,如图:

脚本内容:

#!/bin/bash

PROG_NAME=$0
ACTION=$1

DOMAIN="vpnplease.com"
declare -a OPTION=("jp" "us" "sg")

usage() {
  echo "Usage: $PROG_NAME {test|conn|close|status}"
  exit 1
}

vpn_test() {

  for c in "${OPTION[@]}";do
    for i in `seq 1 3`; do
      proxy="$c$i.$DOMAIN"
      ping -c3 $proxy 2>/dev/null | tail -1 | cut -d'=' -f2 | cut -d'/' -f2 | xargs -I {} echo "$proxy " {} 2>/dev/null &
    done
  done

  children=$(jobs -p | xargs)
  trap 'kill $children >/dev/null 2>&1' SIGINT SIGTERM
  wait
}

get_fastest() {
  vpn_test 2>/dev/null | sort -nk2 | head -1 | awk '{print $1}'
}

vpn_status() {
  for c in "${OPTION[@]}";do
    for i in `seq 1 3`; do
      proxy="$c$i.$DOMAIN"
      scutil --nc status $proxy 2>/dev/null | head -1 | xargs -I {} echo "$proxy " {}
    done
  done
}

vpn_connect() {
  local name=$1

/usr/bin/env osascript <<-EOF
  tell application "System Events"
    tell current location of network preferences
      set VPN to service "$name" -- your VPN name here
      if exists VPN then connect VPN
      repeat while (current configuration of VPN is not connected)
        delay 1
      end repeat
    end tell
  end tell
EOF
}

vpn_disconnect() {
  local name=$(vpn_status | awk '$2~/Connected/{print $1}')
  [ -z $name ] && return 0

/usr/bin/env osascript <<-EOF
  tell application "System Events"
    tell current location of network preferences
      set VPN to service "$name" -- your VPN name here
      if exists VPN then disconnect VPN
    end tell
  end tell
  return
EOF
}

case "$ACTION" in
    test)
        vpn_test
    ;;
    conn)
        vpn_connect $(get_fastest)
    ;;
    close)
        vpn_disconnect
    ;;
    status)
        vpn_status
    ;;
    *)
        usage
    ;;
esac

使用方式:

1) 自动选择最优的vpn进行连接

$ vpn conn

2) 查看连接状态

$ vpn status

jp1.vpnplease.com  Connected
jp2.vpnplease.com  Disconnected
jp3.vpnplease.com  Disconnected
us1.vpnplease.com  Disconnected
us2.vpnplease.com  Disconnected
us3.vpnplease.com  Disconnected
sg1.vpnplease.com  Disconnected
sg2.vpnplease.com  Disconnected

3) 测试网速,时间最小的最优

$ vpn test

jp2.vpnplease.com  76.314
jp1.vpnplease.com  75.793
jp3.vpnplease.com  136.161
sg1.vpnplease.com  169.494
us3.vpnplease.com  242.685
us2.vpnplease.com  249.032
us1.vpnplease.com  266.427
sg2.vpnplease.com  168.750

4) 断开连接

$ vpn close 

选择网速最快的vpn进行连接的脚本》上有4条评论

  1. zhongl


    vpn conn
    101:128: execution error: System Events got an error: Can’t get service "jp2.vpnplease.com" of current location of network preferences. (-1728)

    回复
  2. hongjiang 文章作者

    vpn的名字需要跟地址一致,osascript 脚本里调用vpn的时候,是按照你创建的这个vpn的名称,而不是地址,我这里把地址也作为了vpn的名称。用 scutil –nc list | grep -E “L2TP|PPTP” 看一下你的vpn服务名称列表

    回复
  3. hongjiang 文章作者

    已更新,请用这个:http://hongjiang.info/mac-vpn-script-improved/

    回复

发表评论

电子邮件地址不会被公开。 必填项已用*标注