1

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!

Bijan Soltani
  • 21
  • 1
  • 3
  • Managed to find a solution and posted it here. https://stackoverflow.com/a/69736569/16915238 – JoshZ Oct 28 '21 at 04:23

3 Answers3

2

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.

Mikhail S
  • 133
  • 1
  • 7
0

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.

jurez
  • 4,436
  • 2
  • 12
  • 20
0

It's possible if you are using OpenVPN as proxy

import requests

proxies = {
 'http': 'http://your.proxy.addres:port',
}
r = requests.get('http://somesite.com', proxies=proxies)

check here requests

olli_kahn
  • 157
  • 6