Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use OpenVPN within a Python script

is it generally possible to use an OpenVPN connection solely within the scope of a Python script?

E.g. have something like this

import some_ovpn_library as sol

with sol.connection(config=config):
  # OpenVPN connection is only active for this part of the script and not for anything else that is running in parallel on the same server
  do_something

Thanks!

like image 780
Bijan Soltani Avatar asked Apr 28 '26 09:04

Bijan Soltani


2 Answers

You could try to make openVPN connection as process and kill it at the end of your script like this:

cmd = 'start /b cmd /c "C:\Program Files\OpenVPN\bin\openvpn-gui.exe" --connect config.ovpn'
args = shlex.split(cmd)
x = subprocess.Popen(args, shell=True)
...
...
...
try:
    x.kill()
except:
    pass

It's easy to adapt the sample to your os.

like image 128
Mikhail S Avatar answered Apr 30 '26 23:04

Mikhail S


No. Network functions are in the kernel and work in the same way for all processes.

In Linux, you might possibly do a few tricks with iptables (e.g. tagging packets based on process ID, using different routing tables etc.) but that's not really a good way. If you need such an isolation, consider running Python program in a separate virtual machine.

You can control openvpn from Python though - run it, start it or stop it.

like image 21
jurez Avatar answered Apr 30 '26 21:04

jurez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!