其實從服務端的配置文件里用push命令也可以讓客戶端設置路由,但是用這樣做的路由,走的都是服務端分配的IP地址,不完全符合我的要求,我希望在客戶端連接以後,自動添加從「本地連接」走的路由,這個需求可能很奇怪,但是我的確需要有這樣的路由。
最簡單的方法是連接建立以後手工用route add命令添加,但是人懶,不想打命令,希望系統自動執行,找了N長時間,終於找到。
openvpn的win客戶端安裝目錄時有一個OpenVPN GUI ReadMe.txt文件,裡面講得很清楚:
Run Connect/Disconnect/Preconnect Scripts
-----------------------------------------
There are three diffrent scripts that OpenVPN GUI can execute to help
with diffrent tasks like mapping network drives.
Preconnect If a file named "xxx_pre.bat" exist in the config folder
where xxx is the same as your OpenVPN config file name,
this will be executed BEFORE the OpenVPN tunnel is established.
Connect If a file named "xxx_up.bat" exist in the config folder
where xxx is the same as your OpenVPN config file name,
this will be executed AFTER the OpenVPN tunnel is established.
Disconnect If a file named "xxx_down.bat" exist in the config folder
where xxx is the same as your OpenVPN config file name,
this will be executed BEFORE the OpenVPN tunnel is closed.
我這時有個問題沒解決,我的客戶端配置文件叫client.ovpn,但是當客戶端連接建立時並沒有自動執行一個叫client_up.bat或client.ovpn_up.bat的腳本,我找到的解決辦法是在client.ovpn里添加一句:
up client.ovpn_up.bat
這樣以來,只要客戶端建立連接就會自動執行這個.bat文件。
這個腳本的內容,主要是得到用於和Internet進行連接的網卡的ip地址,然後把這個ip地址用在route add命令里:
route print|findstr /c:" 0.0.0.0" >temp.txt
FOR /F "tokens=4 delims= " %i in (temp.txt) do route add 202.x.x.x mask 255.255.255.255 %i
當有多塊網卡時,使用腳本很難自動判斷應該使用哪塊網卡的ip地址,所以第一句里不使用ipconfig命令,而是使用route print命令,然後過濾出默認網關(0.0.0.0)的一行,再從中取出本地網卡的ip地址,把它做為變數放到route add命令里。
感覺這個腳本中過濾文本的思路和linux shell下差不多,但是windows下腳本的功能比較弱,在linux下這個功能只要一條命令就可以搞定。
另外,以前從未關注過windows下腳本,研究了很多資料,寫出這個腳本以後才覺得其實windows也有文本過濾功能,雖然功能不強,但是還能用用,基本可以滿足一些特殊要求。
Script Order of Execution
--up
Executed after TCP/UDP socket bind and TUN/TAP open.
--tls-verify
Executed when we have a still untrusted remote peer.
--ipchange
Executed after connection authentication, or remote IP address change.
--client-connect
Executed in --mode server mode immediately after client authentication.
--route-up
Executed after connection authentication, either immediately after, or some number of seconds after as defined by the --route-delay option.
--client-disconnect
Executed in --mode server mode on client instance shutdown.
--down
Executed after TCP/UDP and TUN/TAP close.
--learn-address
Executed in --mode server mode whenever an IPv4 address/route or MAC address is added to OpenVPN's internal routing table.
--auth-user-pass-verify
Executed in --mode server mode on new client connections, when the client is still untrusted.
[火星人 ] OpenVPN的Windows客戶端連接后自動添加路由已經有668次圍觀