0%

openvpn连接后执行指定脚本/添加路由

最近在云主机上通过openvpn连接公司环境,拨通vpn连上后却发现有些地址就断开了连接。观察了下,发现公司vpn默认推送的路由太多了,覆盖掉了我这边的某些地址的路由。只能设法在vpn连接后再执行个脚本啥的,替换或是添加下路由。

man了下openvpn,可以发现有这么两个参数:

up: 用于在vpn连接后执行指定的命令:

1
2
3
4
5
6
7
8
--up cmd
Run command cmd after successful TUN/TAP device open (pre --user UID change).

cmd consists of a path to script (or executable program), optionally followed by arguments. The path and arguments may be single- or
double-quoted and/or escaped using a backslash, and should be separated by one or more spaces.

The up command is useful for specifying route commands which route IP traffic destined for private subnets which exist at the other end
of the VPN connection into the tunnel.

script-security: 设置为2后就可以执行用户指定的脚本了:

1
2
3
4
5
6
7
8
--script-security level
This directive offers policy-level control over OpenVPN's usage of external programs and scripts. Lower level values are more restric‐
tive, higher values are more permissive. Settings for level:

0 -- Strictly no calling of external programs.
1 -- (Default) Only call built-in executables such as ifconfig, ip, route, or netsh.
2 -- Allow calling of built-in executables and user-defined scripts.
3 -- Allow passwords to be passed to scripts via environmental variables (potentially unsafe).

于是可以编写一个post_action.sh脚本,放到/etc/openvpn目录下,用这个脚本在vpn连接后替换下路由:

1
2
3
#!/bin/sh

ip route replace 172.16.2.0/24 via 192.168.139.1 dev eth0

添加下执行权限:

1
chmod +x /etc/openvpn/post_action.sh

然后在vpn配置文件中加入配置(或是在命令行中加入这两个参数):

1
2
script-security 2
up /etc/openvpn/post_action.sh

重启vpn,测试就正常了。

update 20210719

如果需要在路由推送后执行命令,可修改为:

1
2
script-security 2
route-up /etc/openvpn/post_action.sh

正好在这里记录下openvpn的systemd service文件写法,以后啥时候要用的时候可以查下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# /lib/systemd/system/vpn_knktc.service
[Unit]
Description=OpenVPN tunnel for test
After=syslog.target network-online.target
Wants=network-online.target
Documentation=man:openvpn(8)
Documentation=https://community.openvpn.net/openvpn/wiki/Openvpn24ManPage
Documentation=https://community.openvpn.net/openvpn/wiki/HOWTO

[Service]
PrivateTmp=true
WorkingDirectory=/etc/openvpn/
ExecStart=/usr/sbin/openvpn --config knktc.ovpn
LimitNPROC=10
DeviceAllow=/dev/null rw
DeviceAllow=/dev/net/tun rw
ProtectSystem=true
ProtectHome=true
KillMode=process

[Install]
WantedBy=multi-user.target
如果我的文字帮到了您,那么可不可以请我喝罐可乐?