从这次开始,把一些技术技巧记录也写在blog里,否则对我这种写博拖延症来说,保持一定频率真太难了。。。拖延症其实都是coding或者干活强迫症造成的,干活强迫症有点让我其他什么都进行困难了。。。废话少说,正题开始,这是一个条件略有复杂和奇特的case,需求可能有些和别人的不同,之前没有搜到特别完美的方案,就把自己的脚本以及折腾过程记录下来。

需求/条件约束

  • 一台Mac OS X(当前是10.7.0)通过PPTP连接到另一端的远程网络(比如从家连接到公司)
  • 远程网络通过ADSL拨号连接互联网,没有动态DNS,但是有某静态IP的web页面公布其地址
  • Mac OS X连接了两个内网(有线和无线),分别为192.168.1.0和192.168.2.0,远程网络的内网是192.168.0.0

连接过程

全程仅用Autormator里添加一个“Run AppleScript”任务,任务中有不少“do shell script xxx”的语句调用命令行工具。代码如下

on run {input, parameters}
  set REMOTEIP to do shell script ¬
  "curl -s http://11.22.33.44:8080/showip | grep -Eo \"([[:digit:]\\.]+)\""
  do shell script "sed -i -e \"s/.* remoteIP.local/" & REMOTEIP & ¬
  " remoteIP.local/g\" /etc/hosts" with administrator privileges
  do shell script "dscacheutil -flushcache"
  do shell script "route -n add -static " & REMOTEIP & ¬
  " 192.168.2.1" with administrator privileges
  tell application "System Events"
    tell current location of network preferences
      set VPNservice to service "VPN NAME IN SYSTEM PREFERENCES"
      if current configuration of VPNservice is not connected then
        connect VPNservice
        repeat while current configuration of VPNservice is not connected
          delay 1
        end repeat
      end if
    end tell
  end tell
  do shell script "route -nv add -net 192.168.0.0/24 10.0.0.2" ¬
  with administrator privileges
  return input
end run

其中“¬”是OPTION+ENTER/RETURN,只是将太长的单行语句折行方便显示用的。

注记

curl -s http://11.22.33.44:8080/showip | grep -Eo "([[:digit:]\\.]+)"

因为暴露远程网络IP地址的静态页面显示的并非一个单独的IP地址,这里用grep把其他无用信息过滤掉,将被扒光的IP地址付给变量REMOTEIP

do shell script "sed -i -e \"s/.* remoteIP.local/" & REMOTEIP & ¬
" remoteIP.local/g\" /etc/hosts" with administrator privileges

我再解释一下上面这行。因为远程网络的IP地址不固定,而Mac OS X里PPTP VPN的目标IP地址目前没有找到好方法用命令行或AppleScript修改,所以这里采用的方法是填写一个本地主机名“remoteIP.local”,然后在 /etc/hosts 文件中写入 “11.22.33.44 remoteIP.local”,这样就避免了在AppleScript或命令行下修改VPN连接目标IP的需求。这个方法虽然有点迂回和龌龊,但是其他更便捷的方法还没发现。缺点还包括每次连接vpn都要修改hosts文件,洁癖表示接受起来鸭梨略大。

route命令是让VPN连接走指定网关的。我是一开机即连上美国VPN的并设置为全局路由,而这里又希望连接办公网络的PPTP VPN不经过美国VPN,就指定了直接从网关经过。

下面的VPN连接代码应该是很容易可以google到的,到处都有解释这里就不多说了。

注意一点是如果命令行操作需要sudo,只需要去掉它并在do shell script “bla bla bla”后加“with administrator privileges”即可。虽然简单的东西也找了挺久,不知道是我不会找还是AppleScript文档比较囧。

其他就没什么了把。先到这里吧:)

blog comments powered by Disqus
  1. kcome posted this