I would like to connect to a VPN using OpenVPN in a python script. In the code I should use the ovpn file of a VPN server (already registered, downloaded and configured), VPN username and password when connecting to VPN servers without the app, and ovpn file with 3 different ports (the ovpn file provides me with the same single IP with 3 different ports)
#I write in this way for illustrative purposes, avoiding writing personal data
remote IP MyPort1_Example
remote IP MyPort2_Example
remote IP MyPort3_Example
I get the error:
Error connecting OpenVPN on port MyPort1_Example: VPN.__init__() got an unexpected keyword argument 'username' (repeated 3 times also for ports MyPort2_Example, MyPort3_Example)
Considering that the VPN server has the same IP with 3 different ports, I’m using a loop. Maybe it’s wrong, I don’t know
from openvpn_api import VPN
def connection_openvpn(self):
try:
# Configure VPN account credentials
username = "aaaa"
password = "bbbb"
# Configure the path of the VPN server configuration file
config_file = "/etc/openvpn/myserverexample.tcp.ovpn"
# Configure a list of VPN ports
#I write in this way for illustrative purposes, avoiding writing personal data
vpn_ports = [MyPort1_Example, MyPort2_Example, MyPort3_Example]
# Iterate over each port and attempt connection
for port in vpn_ports:
try:
# Configure OpenVPN client with credentials and port
client = VPN('127.0.0.1', port, username=username, password=password)
# Start VPN connection
client.connect(config_file)
# Wait for a few seconds for the connection
time.sleep(10)
# Check if the connection is successful
if client.is_connected():
print(f"OpenVPN connection established successfully on port {port}")
# Print connection information
# print("VPN connection IP address:", connection.remote_address)
print("VPN connection IP address:", client.get_virtual_ip())
# Send data through VPN tunnel
client.send('Hello, world!')
# Receive data from the VPN tunnel
data = client.recv()
# Close VPN connection and break the iteration
client.disconnect()
break
else:
print(f"Error during OpenVPN connection on port {port}")
except Exception as e:
print(f"Error during OpenVPN connection on port {port}: {e}")
except Exception as e:
print(f"General error during OpenVPN connection: {e}")