On my Raspbian machine, I want a successful OpenVPN connection to my VPN provider to initiate a Python script, that persistently should run in the background as long as the VPN connection is active. If/when the VPN connection goes offline, I would like to terminate the Python script.
My thinking is this: the up
and down
flags in OpenVPN's configuration file will execute shell scripts that start and stop a systemd
service. That service Requires
the openvpn.service
and cannot (should not) run without it.
What's complicating things is that I want to run the Python script inside a Virtualenv
which in bash is accessible by alias coding="cd /home/p1/Coding/Python/Virtual/py279/bin; source activate; cd /home/p1/Coding/Python/Projects"
. The location of the Python file is in the latter folder.
However, it is my understanding that systemd
cannot run command lines in the way as the alias coding
above would.
So I guess a solution could be for systemd
to execute a .service
that executes a .sh
script that in turn executes the .py
Python script.
Schematic:
OpenVPN
up
→ovpn_up.sh
→sudo systemctl start vpn_up.service
→ExecStart=/path/to/start_pythonscript.sh
→coding; python my_script.py
OpenVPN
down
→ovpn_down.sh
→sudo systemctl stop vpn_up.service
My assumption is that there are a few caveats and/or problems with this, especially regarding how to properly terminate the Python script.
Questions:
- Is this feasible?
- What sections and service commands in the service files are needed for this to work?
- Are there any special considerations that must be made for this overall arrangement, e.g. proper clean-up after terminating the Python script, what happens at system shutdown/reboot, etc?
Best Answer
You should first simplify your alias, there is no need to do the activate stuff. What is important is the first, shebang, line of the python script. It should read:
If the script is executable (
chmod +x script_name
) then the above line make sure that the python installed in virtualenv is called, and that ensures that packages installed in the virtualenv are taken.You can make an alias to the script, or put the script in some directory that is in your PATH.
In the systemd service file you should use the full path to the script. Such a script could look like:
The above assumes your python script is in
/root/bin/application
and that it starts if passed in thestart
commandline argument, and that when it is called withstop
, somehow the second invocation knows how to notify thestart
ed application and gracefully shut down. IIRC if you don't have aExecStop
systemd will try to stop/kill your app, which you could catch with a signal handler