Preface a previous blog introduced the use of update-rc.d to manage Ubuntu boot start running program, links see: update-rc.d management Ubuntu boot Startup Program, at that time want to solve the problem is boot automatic connection VPN, however, this method may cause the VPN process to become dead, because the VPN connection is related to the NIC status, this section describes how to automatically run a custom program after the network is connected in the Debian/Ubuntu release, run scripts in the corresponding directory in/etc/Network/before, after, and before, and after the network is established.
- If-down.d -- before Network Shutdown
- If-post-down.d -- after the network is turned off
- If-pre-up.d-before network creation
- If-up.d-after the network is built
Idea (1) After the network is established, we need to add a script to automatically connect to the VPN under the/etc/Network/if-up.d/directory, in this way, you can connect to the VPN as long as it is in the network state.
#! /Bin/bash # variable definition Path =/sbin:/usr/sbin:/bin: /usr/binconfig_path = "/home/wangzhengyi/cloud-1/openvpn-client.ovpn" # import environment variables. /lib/LSB/init-functionsexport Path = $ path # Run openvpnlog_daemon_msg "starting Client openvpn" nohup openvpn $ config_path after the network is established
(2) Before the network is disconnected, we need to stop all VPN processes to prevent program bugs.
- First, let's talk about a bug where scripts in Ubuntu's/etc/Network/if-down.d/and/etc/Network/if-post-down.d/directory won't be executed when the network is disconnected, why is it not found by Google?
- It should be emphasized that there should be no way of thinking. It takes several hours to solve this problem, that is, the way of thinking. You can consider writing a monitoring script to check whether the network is smooth, if the network is down, kill all VPN processes. Then, the crontab runs regularly and the script code is used.
#! /Bin/bash # variable definition URLs = ("www.baidu.com" "www.sogou.com" "www.sososo.com") http_code = ("200" "301" "302" "404 ") count = $ {# URLs [*]} connected = 0 # network detection for (I = 0; I <$ count; I ++ )) dourl =$ {URLs [$ I]} result = $ (curl-O/dev/null-S-M 10-w % {http_code} $ URL) for flag in $ {http_code [*]} doif [$ flag = $ result]; thenconnected =$ (expr $ connected + 1) fidonedone # Kill all VPN processes when the network is down if [$ connected-EQ 0]; thenvpn_pids = $ (PS-Aux | grep-I 'openvp' | grep-V 'grep' | awk '{print $2 }') for PID in $ {vpn_pids [*]} dokill-9 $ piddonefi
Crontab scheduled run
* * * * * monitor_scripts
Note that you have a better method. You are welcome to leave a message. I hope to discuss it with you!