How do I run a script after OpenVPN has connected successfully?
Solution 1:
network-manager-openvpn
does not provide such functionality, you have to use openvpn
directly.
Pass --script-security 2 --up /path/to/your/script
to it when connecting. If you're using a configuration file located at /etc/openvpn/
, append the next lines to your configuration file:
script-security 2
# run /etc/openvpn/up.sh when the connection is set up
up /etc/openvpn/up.sh
From the OpenVPN manpage:
--script-security level [method] This directive offers policy-level control over OpenVPN’s usage of external programs and scripts. Lower level values are more restrictive, 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). --up cmd Shell command to run after successful TUN/TAP device open (pre --user UID change). The up script 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 Order of Execution --up Executed after TCP/UDP socket bind and TUN/TAP open. --down Executed after TCP/UDP and TUN/TAP close.
There are more events for script execution, those can be found on the manual page.
Create /etc/openvpn/up.sh
, and give it execute permissions (say, 755 or 700). Example content for adding an IPv6 address and route (shown for educational purposes, do not copy it directly):
#!/bin/sh
# add an IPv6 address to device $dev (environment variable)
ip -6 addr add 2001:db8::1:2/112 dev $dev
# and the IPv6 route for this net using gateway 2001:db8::1
ip -6 route add 2001:db8::1:0/112 via 2001:db8::1 dev $dev
Note that this up
script is run as root. If you have not specified a User
and Group
setting, OpenVPN will run scripts like down
as root too.
Solution 2:
As that is a quite old thread I'm not sure if still of interest. If you still want to use the NetworkManager to connect to a VPN you can add a simple udev rule like that:
KERNEL=="vpn0", RUN+="/PATH_TO_THE_SCRIPT/SCRIPT_NAME"
This should run any script after the VPN is created.