You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

vpngen.py 2.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. from enum import Enum
  2. import os
  3. import os.path
  4. import re
  5. import shutil
  6. class VpnGenError(Enum):
  7. Success = 0,
  8. VpnAlreadyExists = 1,
  9. VpnDoesNotExists = 2,
  10. ClientAlreadyExists = 3,
  11. ClientDoesNotExists = 4
  12. class VpnGen:
  13. default_config_base_dir = ""
  14. default_config_file = ""
  15. ovpn_config_path = ""
  16. def __init__(self, default_config_path, ovpn_config_path):
  17. self.default_config_base_dir = default_config_path
  18. self.default_config_file = "%s.conf" % default_config_path
  19. self.ovpn_config_path = ovpn_config_path
  20. def f7(self, seq):
  21. seen = set()
  22. seen_add = seen.add
  23. return [x for x in seq if not (x in seen or seen_add(x))]
  24. def _find_vars(self, content):
  25. variables = re.findall('\$\{([^}]+)}', content)
  26. variables = self.f7(variables)
  27. return variables
  28. def get_vpn_vars(self):
  29. with open(self.default_config_file, "r") as f:
  30. default_config = f.read()
  31. variables = self._find_vars(default_config)
  32. variables += ["KEY_COUNTRY", "KEY_PROVINCE", "KEY_CITY", "KEY_ORG", "KEY_EMAIL"]
  33. return variables
  34. def create_vpn(self, vpn_name, variables):
  35. base_dir = "%s%s%s" % (self.ovpn_config_path, os.sep, vpn_name)
  36. conf_file = "%s.conf" % base_dir
  37. if os.path.exists(base_dir) or os.path.exists(conf_file):
  38. return VpnGenError.VpnAlreadyExists
  39. with open(self.default_config_file, "r") as f:
  40. default_config = f.read()
  41. variables['name'] = vpn_name
  42. for variable in variables:
  43. default_config = default_config.replace("${%s}" % variable, variables[variable])
  44. os.makedirs(base_dir)
  45. with open(conf_file, "w") as f:
  46. f.write(default_config)
  47. os.rmdir(base_dir)
  48. shutil.copytree(self.default_config_base_dir, base_dir)
  49. return VpnGenError.Success
  50. def remove_vpn(self, vpn_name):
  51. return VpnGenError.ClientDoesNotExists
  52. def create_client(self, vpn_name, client_name, variables):
  53. return VpnGenError.ClientDoesNotExists
  54. def remove_client(self, vpn_name, client_name):
  55. return VpnGenError.ClientDoesNotExists
  56. def rebuild_clients(self, vpn_name):
  57. return VpnGenError.ClientDoesNotExists