Providers

AWS

class auto_proxy_vpn.providers.aws.aws_proxy.AwsProxy(manager: ProxyManagerAws, instance_id: str, group_id: str, name: str, ip: str, port: int, region: str, proxy_instance: str = '', allowed_ips: list[str] = [], is_async: bool = False, user: str = '', password: str = '', logger: Logger | None = None, reload: bool = False, on_exit: Literal['keep', 'destroy'] = 'destroy')[source]

Bases: BaseProxy

__init__(manager: ProxyManagerAws, instance_id: str, group_id: str, name: str, ip: str, port: int, region: str, proxy_instance: str = '', allowed_ips: list[str] = [], is_async: bool = False, user: str = '', password: str = '', logger: Logger | None = None, reload: bool = False, on_exit: Literal['keep', 'destroy'] = 'destroy')[source]

Represent an AWS EC2-based proxy instance.

This object stores proxy metadata and runtime state and can be initialized either for a newly created proxy EC2 instance or by reloading an existing one.

Parameters:
  • manager (ProxyManagerAws) – Manager instance that owns AWS SDK clients and credentials used by this proxy.

  • instance_id (str) – AWS EC2 instance ID for the proxy VM.

  • group_id (str) – AWS security group ID associated with the proxy instance.

  • name (str) – Proxy name stored in EC2 tags.

  • ip (str) – Public IPv4 address of the proxy.

  • port (int) – Proxy listening TCP port.

  • region (str) – AWS region where the proxy resources are deployed.

  • proxy_instance (str, optional) – EC2 instance type used for this proxy (for example 't3.micro'). Defaults to ''.

  • allowed_ips (list[str], optional) – Source IPs/ranges allowed to connect to the proxy. Used for startup/reload metadata. Defaults to an empty list.

  • is_async (bool, optional) – If True, do not block waiting for full startup/teardown completion. Defaults to False.

  • user (str, optional) – Basic-auth username configured in Squid. Defaults to ''.

  • password (str, optional) – Basic-auth password configured in Squid. Defaults to ''.

  • logger (Logger or None, optional) – Logger used for lifecycle and status messages. Defaults to None.

  • reload (bool, optional) – If True, this object is being created from an existing proxy and emits reload-oriented log messages. Defaults to False.

  • on_exit ({'keep', 'destroy'}, optional) – Behavior when the proxy is closed. 'destroy' terminates cloud resources and 'keep' leaves them running. Defaults to 'destroy'.

Raises:

ValueError – If on_exit is not 'keep' or 'destroy'.

is_active(wait: bool = False) bool[source]

Checks if proxy is active.

Parameters:

wait (bool) – Always wait until the proxy is active, even if it is asynchronous.

class auto_proxy_vpn.providers.aws.aws_proxy.ProxyManagerAws(ssh_key: list[dict[str, str] | str] | dict[str, str] | str, credentials: dict[str, str] | None = None, log: bool = True, log_file: str | None = None, log_format: str = '%(asctime)-10s %(levelname)-5s %(message)s', logger: Logger | None = None)[source]

Bases: BaseProxyManager[AwsProxy]

__init__(ssh_key: list[dict[str, str] | str] | dict[str, str] | str, credentials: dict[str, str] | None = None, log: bool = True, log_file: str | None = None, log_format: str = '%(asctime)-10s %(levelname)-5s %(message)s', logger: Logger | None = None)[source]

Create a manager that provisions AWS EC2 proxy instances.

This initializer validates AWS credentials and SSH key input, configures logging, imports AWS SDK clients, and loads available regions and size mappings used by the manager.

Parameters:
  • ssh_key (list[dict[str, str] | str] | dict[str, str] | str) – SSH key configuration for created instances. Accepted forms are a single public key string, a dict with {'name': ..., 'public_key': ...}, a list mixing both forms, or a file path containing one public key per line.

  • credentials (dict[str, str] or None, optional) – AWS credential configuration. Supported keys are AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY. When omitted, environment variables are used. Defaults to None.

  • log (bool, optional) – Enable logging for manager actions. Defaults to True.

  • log_file (str or None, optional) – File path for logging output. If None, logging output goes to the terminal. Defaults to None.

  • log_format (str, optional) – Format string used when creating an internal logger. Defaults to '%(asctime)-10s %(levelname)-5s %(message)s'.

  • logger (Logger or None, optional) – Custom logger instance. When provided, log_file and log_format are ignored. Defaults to None.

Raises:
  • ValueError – If AWS credentials are missing both in credentials and in environment variables.

  • TypeError – If ssh_key has an invalid structure or no valid SSH keys are found.

  • ImportError – If required AWS SDK packages are not installed.

classmethod from_config(config: AwsConfig | None = None, runtime_config: ManagerRuntimeConfig | None = None) ProxyManagerAws[source]

Create a ProxyManagerAws instance from an AwsConfig object and a ManagerRuntimeConfig.

get_proxy(port: int = 0, size: Literal['small', 'medium', 'large'] = 'medium', region: str = '', auth: dict[Literal['user', 'password'], str] = {}, allowed_ips: str | list[str] = [], is_async: bool = False, retry: bool = True, proxy_name: str = '', on_exit: Literal['keep', 'destroy'] = 'destroy') AwsProxy[source]

Create and start an AWS-based proxy instance.

The method randomly selects (or validates) a region, prepares authentication and allowed source IPs, starts the proxy EC2 resources, and returns an AwsProxy wrapper.

Parameters:
  • port (int, optional) – TCP port for the proxy. If 0, a random port between 10000 and 65000 is selected. Defaults to 0.

  • size ({'small', 'medium', 'large'}, optional) – Proxy instance size profile. Defaults to 'medium'.

  • region (str, optional) – Preferred AWS region. If empty, a random region is selected from available regions for the selected size. Defaults to ''.

  • auth (dict, optional) – Basic-auth credentials as {'user': ..., 'password': ...}. If empty, no basic authentication is configured. Defaults to an empty dict.

  • allowed_ips (str or list[str], optional) – Source IP/range(s) allowed to access the proxy. Can be a single string or a list. The caller public IP is automatically added if missing. Defaults to an empty list.

  • is_async (bool, optional) – If True, do not wait for full VM startup before returning. Defaults to False.

  • retry (bool, optional) – Enable retry when startup fails and region was chosen randomly. Ignored when a specific region is provided. Defaults to True.

  • proxy_name (str, optional) – Explicit proxy name. If empty, a unique name of the form proxyN is generated. Defaults to ''.

  • on_exit ({'keep', 'destroy'}, optional) – Behavior when the returned proxy is closed. 'destroy' removes cloud resources; 'keep' leaves them running. Defaults to 'destroy'.

Returns:

Proxy wrapper object for the created AWS proxy.

Return type:

AwsProxy

Raises:
  • NameError – If proxy_name is provided and already exists.

  • ValueError – If region is provided but not available.

  • TypeError – If auth is not a dict, or if allowed_ips has an invalid IP/range format.

  • KeyError – If auth is provided without both 'user' and 'password' keys.

  • Exception – If proxy startup fails and no valid retry path remains.

get_proxy_by_name(name: str, is_async: bool = False, on_exit: Literal['destroy', 'keep'] = 'destroy') AwsProxy[source]

Reload an existing AWS proxy instance by its name.

The method validates that the proxy exists, retrieves EC2 metadata, reads the remote Squid configuration to recover proxy settings (port, allowed IPs and optional basic-auth credentials), and returns a reloaded AwsProxy object.

Parameters:
  • name (str) – Name tag of the AWS proxy to load.

  • is_async (bool, optional) – If True, the returned proxy object uses asynchronous behavior for lifecycle operations. Defaults to False.

  • on_exit ({'destroy', 'keep'}, optional) – Behavior when the returned proxy is closed. 'destroy' removes resources and 'keep' leaves them running. Defaults to 'destroy'.

Returns:

Reloaded proxy instance bound to the existing AWS resources.

Return type:

AwsProxy

Raises:
  • NameError – If no running proxy with name exists.

  • ConnectionError – If the Squid configuration cannot be read through SSH.

  • ValueError – If the proxy port cannot be extracted from the instance config.

get_running_proxy_names(return_region: bool = False) list[str] | list[tuple[str, str]][source]

List currently running AWS proxies discovered across regions.

The method queries every available AWS region concurrently and returns either only proxy names or name/region pairs.

Parameters:

return_region (bool, optional) – If True, return tuples containing (name, region). If False, return only proxy names. Defaults to False.

Returns:

List of proxy names when return_region is False. When True, returns a flattened list of name/region pairs.

Return type:

list[str]

auto_proxy_vpn.providers.aws.aws_utils.get_region_instances(proxy_manager: ProxyManagerAws, region: str) list[tuple[str, str]][source]

List active proxy instances in a specific AWS region.

This helper queries EC2 instances tagged as proxy resources and returns their names paired with the region where they are running.

Parameters:
  • proxy_manager (ProxyManagerAws) – Manager instance that provides configured boto3 access and AWS credentials.

  • region (str) – AWS region name used to query EC2 instances.

Returns:

List of tuples (instance_name, region) for instances in pending or running states.

Return type:

list[tuple[str, str]]

Raises:

Exception – Propagates exceptions raised by the AWS SDK request.

auto_proxy_vpn.providers.aws.aws_utils.start_proxy(proxy_manager: ProxyManagerAws, proxy_name: str, port: int, region: str, machine_type: str, allowed_ips: list[str], user: str = '', password: str = '', is_async: bool = False) tuple[str, str, str, bool][source]

Create and start an EC2 instance configured as an HTTP proxy.

This helper resolves the latest AMI that matches configured filters, creates a dedicated security group, opens SSH/proxy ingress for allowed IPs, and launches a tagged EC2 instance with Squid startup user data.

Parameters:
  • proxy_manager (ProxyManagerAws) – Manager instance that provides boto3 clients/resources, credentials, AMI filters, and SSH keys.

  • proxy_name (str) – Name used for the EC2 instance tag and associated security group.

  • port (int) – TCP port exposed by the proxy service.

  • region (str) – AWS region where the proxy instance is created.

  • machine_type (str) – EC2 instance type (for example 't3.micro').

  • allowed_ips (list[str]) – Source IPs/CIDRs allowed to access SSH and proxy ports.

  • user (str, optional) – Basic-auth username for Squid configuration. Defaults to ''.

  • password (str, optional) – Basic-auth password for Squid configuration. Defaults to ''.

  • is_async (bool, optional) – If True, return before waiting for instance running state. Defaults to False.

Returns:

A tuple (public_ip, instance_id, security_group_id, error) where error is True when provisioning cannot continue or no capacity is available.

Return type:

tuple[str, str, str, bool]

Raises:
exception auto_proxy_vpn.providers.aws.aws_exceptions.AwsUnauthorizedOperationError(*args)[source]

Bases: Exception

Google Cloud

class auto_proxy_vpn.providers.google.google_proxy.GoogleProxy(manager: ProxyManagerGoogle, name: str, ip: str, port: int, project: str, region: str, zone: str, proxy_instance: str = '', allowed_ips: list[str] = [], is_async: bool = False, user: str = '', password: str = '', logger: Logger | None = None, reload: bool = False, on_exit: Literal['keep', 'destroy'] = 'destroy')[source]

Bases: BaseProxy

__init__(manager: ProxyManagerGoogle, name: str, ip: str, port: int, project: str, region: str, zone: str, proxy_instance: str = '', allowed_ips: list[str] = [], is_async: bool = False, user: str = '', password: str = '', logger: Logger | None = None, reload: bool = False, on_exit: Literal['keep', 'destroy'] = 'destroy')[source]

Represent a Google Cloud VM-based proxy instance.

This object stores proxy metadata and lifecycle state, and can be initialized either for a newly created instance or by reloading an existing one.

Parameters:
  • manager (ProxyManagerGoogle) – Manager instance that owns the Google Compute clients used by this proxy.

  • name (str) – Google Compute Engine instance name.

  • ip (str) – Public IP address of the proxy instance. Can be empty while the instance is still starting.

  • port (int) – Proxy listening port.

  • project (str) – Google Cloud project ID where the instance exists.

  • region (str) – Region of the proxy instance.

  • zone (str) – Zone of the proxy instance.

  • proxy_instance (str, optional) – Machine type used for the instance (for example 'e2-micro'). Defaults to ''.

  • allowed_ips (list[str], optional) – Allowed IPs/ranges. Defaults to an empty list.

  • is_async (bool, optional) – If True, the proxy may be returned before full startup completion. If the proxy is asynchronous on exit, it won’t wait for full shutdown. Defaults to False.

  • user (str, optional) – Basic-auth username configured for the proxy. Defaults to ''.

  • password (str, optional) – Basic-auth password configured for the proxy. Defaults to ''.

  • logger (Logger or None, optional) – Logger used for status and lifecycle messages. Defaults to None.

  • reload (bool, optional) – If True the proxy is already running and the object is being reloaded with its info. In this case, the constructor will skip initial activation checks for an already running instance. Defaults to False.

  • on_exit ({'keep', 'destroy'}, optional) – Defines behavior when the proxy is closed: keep the cloud resource or destroy it. Defaults to 'destroy'.

Raises:

ValueError – If on_exit is not 'keep' or 'destroy'.

is_active(wait: bool = False) bool[source]

Checks if proxy is active.

Parameters:

wait (bool) – Always wait until the proxy is active, even if it is asynchronous.

class auto_proxy_vpn.providers.google.google_proxy.ProxyManagerGoogle(ssh_key: list[dict[str, str] | str] | dict[str, str] | str, project: str, credentials: str = '', log: bool = True, log_file: str | None = None, log_format: str = '%(asctime)-10s %(levelname)-5s %(message)s', logger: Logger | None = None)[source]

Bases: BaseProxyManager[GoogleProxy]

__init__(ssh_key: list[dict[str, str] | str] | dict[str, str] | str, project: str, credentials: str = '', log: bool = True, log_file: str | None = None, log_format: str = '%(asctime)-10s %(levelname)-5s %(message)s', logger: Logger | None = None)[source]

Create a manager that provisions Google Cloud proxy instances on demand.

The manager validates credentials, configures SSH keys and logging, initializes Google Compute Engine clients, and loads available regions/zones plus the latest Ubuntu image used for proxy instances.

Parameters:
  • project (str) – Google Cloud project ID where proxy instances are created.

  • ssh_key (list[dict[str, str] | str] | dict[str, str] | str) – SSH key configuration for created instances, provided either as a single public key string, a dictionary with keys {'name': ..., 'public_key': ...}, a list mixing both formats, or a file path containing one public key per line.

  • credentials (str, optional) – Path to a Google service-account JSON credentials file. Used only when GOOGLE_APPLICATION_CREDENTIALS is not already set in the environment. Defaults to ''.

  • log (bool, optional) – Enable logging for manager actions. Defaults to True.

  • log_file (str or None, optional) – File path for logging output. If None, logs are emitted to the terminal. Defaults to None.

  • log_format (str, optional) – Format string used by logging when an internal logger is created. Defaults to '%(asctime)-10s %(levelname)-5s %(message)s'.

  • logger (Logger or None, optional) – Custom logger instance. When provided, log_file and log_format are ignored. Defaults to None.

Raises:
  • GoogleAuthException – If credentials are required but neither GOOGLE_APPLICATION_CREDENTIALS nor credentials is provided.

  • TypeError – If ssh_key has an invalid structure or no valid SSH keys are found.

  • ImportError – If google-cloud-compute is not installed.

Examples

Use environment-based credentials with a context manager:

os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'my_google_credentials.json'
manager = ProxyManagerGoogle(
    'my-google-project',
    ssh_key='ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQC2...'
)
with manager.get_proxy() as proxy:
    result = requests.get('https://google.com', proxies=proxy.get_proxy())

Pass credentials explicitly and close manually:

manager = ProxyManagerGoogle(
    'my-google-project',
    credentials='my_google_credentials.json'
)
proxy = manager.get_proxy()
try:
    # Use the proxy
    pass
finally:
    proxy.close()
classmethod from_config(config: GoogleConfig | None = None, runtime_config: ManagerRuntimeConfig | None = None) ProxyManagerGoogle[source]

Create a ProxyManagerGoogle instance from a GoogleConfig object and a ManagerRuntimeConfig.

get_proxy(port: int = 0, size: Literal['small', 'medium', 'large'] = 'medium', region: str = '', auth: dict[Literal['user', 'password'], str] = {}, allowed_ips: str | list[str] = [], is_async: bool = False, retry: bool = True, proxy_name: str = '', on_exit: Literal['keep', 'destroy'] = 'destroy') GoogleProxy[source]

Create and start a Google Cloud proxy instance.

Parameters:
  • port (int, optional) – TCP port for the proxy. If 0, a random port between 10000 and 65000 will be selected. Defaults to 0.

  • size ({'small', 'medium', 'large'}, optional) – Instance size. Defaults to 'medium'.

  • region (str, optional) – Preferred Google Cloud region name. If provided, selection is restricted to this region. If empty, a region and zone are chosen at random from available regions.

  • auth (dict, optional) – Authentication credentials with keys 'user' and 'password'. If omitted, no authentication is configured. Defaults to an empty dict.

  • allowed_ips (str or list[str], optional) – A single IP string or a list of IPs/ranges allowed to connect to the proxy. The caller’s public IP is added automatically if not present. Defaults to an empty list.

  • is_async (bool, optional) – If True, start the instance asynchronously (do not wait for it to be ready). Defaults to False.

  • retry (bool, optional) – Whether to allow retrying across other regions when selecting a zone. If a specific region is provided, retries are disabled. Defaults to True.

  • proxy_name (str, optional) – Explicit name for the proxy instance. If omitted a unique name of the form 'proxyN' is generated.

  • on_exit ({'keep', 'destroy'}, optional) – Behavior when the returned GoogleProxy is closed. Defaults to 'destroy'.

Returns:

GoogleProxy instance that represents the started proxy instance (contains name, ip, port, project, region, zone, size and lifecycle info).

Return type:

GoogleProxy

Raises:
  • NameError – If proxy_name is provided and already exists.

  • ValueError – If the provided region does not exist or is not available.

  • TypeError – If auth is not a dict, or allowed_ips contains entries with an invalid format.

  • KeyError – If auth is provided but missing the required keys 'user' or 'password'.

  • Exception – If instance creation fails or the instance does not start correctly.

get_proxy_by_name(name: str, is_async: bool = False, on_exit: Literal['destroy', 'keep'] = 'destroy') GoogleProxy[source]

Load an existing Google Cloud proxy instance by its name.

This method looks up a running instance, extracts its public IP, proxy port and optional authentication credentials from the startup script metadata, and returns a reloaded GoogleProxy wrapper.

Parameters:
  • name (str) – Name of the proxy instance in Google Cloud.

  • is_async (bool, optional) – If True, do not wait for full startup before returning. Defaults to False.

  • on_exit ({'destroy', 'keep'}, optional) – Behavior when the returned GoogleProxy is closed. Defaults to 'destroy'.

Returns:

GoogleProxy object bound to the existing instance.

Return type:

GoogleProxy

Raises:
  • NameError – If no proxy instance with the given name exists.

  • ValueError – If the proxy port cannot be parsed from the instance startup script.

  • ValueError – If the startup script cannot be found in the instance metadata.

get_running_proxy_names() list[str][source]

Get list of running proxy names

auto_proxy_vpn.providers.google.google_utils.wait_for_extended_operation(operation, timeout: int = 200) Any[source]

Waits for the extended (long-running) operation to complete.

If the operation is successful, it will return its result. If the operation ends with an error, an exception will be raised. If there were any warnings during the execution of the operation they will be printed to sys.stderr.

Parameters:
  • operation – A long-running operation you want to wait on.

  • timeout (int) – How long (in seconds) to wait for operation to finish. If None, wait indefinitely.

Returns:

Whatever the operation.result() returns.

Return type:

object

Raises:
auto_proxy_vpn.providers.google.google_utils.get_avaliable_regions_by_size(compute_v1, machine_types_client, project: str, instance_proxy_sizes: dict[Literal['small', 'medium', 'large'], str]) tuple[list[tuple[str, list[str]]], dict[Literal['small', 'medium', 'large'], list[str] | list[tuple[str, list[str]]]]][source]

Returns a list of all available regions and zones in Google Cloud, and a mapping of instance sizes to their available regions.

Parameters:
  • compute_v1 – The Google Compute Engine client library.

  • machine_types_client – The Google Compute Engine MachineTypesClient instance.

  • project (str) – The Google Cloud project ID.

  • instance_proxy_sizes (dict) – A dictionary mapping size labels (“small”, “medium”, “large”) to Google Cloud machine type slugs.

Returns:

A list of tuples, where each tuple contains a region name and a list of its zones. And a dictionary mapping size labels to either a list of regions or a list of tuples (region name and its zones) where that size is available.

Return type:

tuple

Raises:

Exception – Propagates exceptions raised by the Google Compute API clients while fetching regions and machine types.

auto_proxy_vpn.providers.google.google_utils.start_proxy(proxy_manager: ProxyManagerGoogle, proxy_name: str, port: int, region: str, zone: str, zones: list[str], machine_type: str, allowed_ips: list[str], user: str = '', password: str = '', is_async: bool = False, firewall: bool = True) tuple[str, bool][source]

Create and start a Google Compute Engine proxy instance.

This helper optionally creates a firewall rule, provisions a VM configured with a Squid startup script, waits for completion when requested, and returns the instance public IP address.

Parameters:
  • proxy_manager (ProxyManagerGoogle) – Manager instance that provides Google Compute clients and project configuration.

  • proxy_name (str) – Name of the VM and related firewall/tag resources.

  • port (int) – Proxy TCP port exposed by Squid.

  • region (str) – Google Cloud region used to resolve the default subnet.

  • zone (str) – Google Cloud zone where the VM is created.

  • machine_type (str) – Compute Engine machine type slug (for example 'e2-micro').

  • allowed_ips (list[str]) – Source IPs/ranges allowed to access the proxy port.

  • user (str, optional) – Basic-auth username injected in the startup script. Defaults to ''.

  • password (str, optional) – Basic-auth password injected in the startup script. Defaults to ''.

  • is_async (bool, optional) – If True, do not wait for the create operation to finish before continuing. Defaults to False.

  • firewall (bool, optional) – If True, create a firewall rule named {proxy_name}-firewall before creating the VM. Defaults to True.

Returns:

(public_ip, error) where public_ip is the assigned IPv4 address and error indicates whether provisioning failed.

Return type:

tuple[str, bool]

Raises:

Exception – Propagates exceptions raised by the Google Compute API clients while creating firewall rules, creating the instance, or fetching instance network information.

exception auto_proxy_vpn.providers.google.google_exceptions.GoogleAuthException(*args)[source]

Bases: Exception

Azure

class auto_proxy_vpn.providers.azure.azure_proxy.AzureProxy(manager: ProxyManagerAzure, name: str, ip: str, port: int, region: str, proxy_instance: str = '', allowed_ips: list[str] = [], is_async: bool = False, user: str = '', password: str = '', logger: Logger | None = None, reload: bool = False, on_exit: Literal['keep', 'destroy'] = 'destroy')[source]

Bases: BaseProxy

__init__(manager: ProxyManagerAzure, name: str, ip: str, port: int, region: str, proxy_instance: str = '', allowed_ips: list[str] = [], is_async: bool = False, user: str = '', password: str = '', logger: Logger | None = None, reload: bool = False, on_exit: Literal['keep', 'destroy'] = 'destroy')[source]

Represent an Azure VM-based proxy instance.

This object stores proxy metadata and lifecycle state and can be initialized either for a newly created proxy VM or by reloading an existing one.

Parameters:
  • manager (ProxyManagerAzure) – Manager instance that owns Azure SDK clients and resources used by this proxy.

  • name (str) – Proxy resource group / VM base name.

  • ip (str) – Public IPv4 address of the proxy. May be empty while the VM is still provisioning.

  • port (int) – Proxy listening TCP port.

  • region (str) – Azure region where the proxy resources are deployed.

  • proxy_instance (str, optional) – Azure VM size used for this proxy (for example 'Standard_B1s'). Defaults to ''.

  • allowed_ips (list[str], optional) – Source IPs/ranges allowed to connect to the proxy. Used for startup/retry metadata. Defaults to an empty list.

  • is_async (bool, optional) – If True, do not block waiting for full startup completion. Defaults to False.

  • user (str, optional) – Basic-auth username configured in Squid. Defaults to ''.

  • password (str, optional) – Basic-auth password configured in Squid. Defaults to ''.

  • logger (Logger or None, optional) – Logger used for lifecycle and status messages. Defaults to None.

  • reload (bool, optional) – If True and ip is already set, skip initial activation checks for a previously created proxy. Defaults to False.

  • on_exit ({'keep', 'destroy'}, optional) – Behavior when the proxy is closed. 'destroy' removes Azure resources and 'keep' leaves them running. Defaults to 'destroy'.

Raises:

ValueError – If on_exit is not 'keep' or 'destroy'.

is_active(wait=False) bool[source]

Checks if proxy is active.

Parameters:

wait (bool) – Always wait until the proxy is active, even if it is asynchronous.

class auto_proxy_vpn.providers.azure.azure_proxy.ProxyManagerAzure(ssh_key: list[dict[str, str] | str] | dict[str, str] | str, credentials: str | dict[str, str] = '', log: bool = True, log_file: str | None = None, log_format: str = '%(asctime)-10s %(levelname)-5s %(message)s', logger: Logger | None = None)[source]

Bases: BaseProxyManager[AzureProxy]

__init__(ssh_key: list[dict[str, str] | str] | dict[str, str] | str, credentials: str | dict[str, str] = '', log: bool = True, log_file: str | None = None, log_format: str = '%(asctime)-10s %(levelname)-5s %(message)s', logger: Logger | None = None)[source]

Create a manager that provisions Azure proxy virtual machines.

This initializer validates Azure credentials and SSH key input, configures logging, imports Azure SDK clients, and loads available VM regions and size mappings used by the manager.

To obtain Azure credentials, you need to create a new subscription and register an application in Azure Active Directory with the appropriate permissions. Then, you can provide the subscription ID, client ID, client secret, and tenant ID either as environment variables or directly as a dictionary to the manager.

With azure cli you can easily obtain the required credentials by running:

$ az ad sp create-for-rbac –name “my-proxy-manager” –role contributor –scopes /subscriptions/{subscription-id}

And save in a .env file or set the environment variables directly:

appId → AZURE_CLIENT_ID

password → AZURE_CLIENT_SECRET

tenant → AZURE_TENANT_ID

Parameters:
  • ssh_key (list[dict[str, str] | str] | dict[str, str] | str) – SSH key configuration for created VMs. Accepted forms are a single public key string, a dict with {'name': ..., 'public_key': ...}, a list mixing both forms, or a file path containing one public key per line.

  • credentials (str or dict[str, str], optional) – Azure credential configuration. Supported values are: subscription ID as a string, dict containing AZURE_SUBSCRIPTION_ID, optionally with AZURE_CLIENT_ID, AZURE_CLIENT_SECRET and AZURE_TENANT_ID, or empty value to rely on environment variables. Defaults to ''.

  • log (bool, optional) – Enable logging for manager actions. Defaults to True.

  • log_file (str, optional) – File path for logging output. If empty, logging output goes to the terminal. Defaults to ''.

  • log_format (str, optional) – Format string used when creating an internal logger. Defaults to '%(asctime)-10s %(levelname)-5s %(message)s'.

  • logger (Logger or None, optional) – Custom logger instance. When provided, log_file and log_format are ignored. Defaults to None.

Raises:
  • ValueError – If subscription information is missing both in credentials and in AZURE_SUBSCRIPTION_ID environment variable.

  • TypeError – If ssh_key has an invalid structure or no valid SSH keys are found.

  • ImportError – If required Azure SDK packages are not installed.

Examples

Use environment-based credentials with a context manager:

manager = ProxyManagerAzure(
    ssh_key='ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQC2...'
)
with manager.get_proxy() as proxy:
    result = requests.get('https://google.com', proxies=proxy.get_proxy())

Pass credentials explicitly and close manually:

manager = ProxyManagerAzure(
    credentials={
        'AZURE_SUBSCRIPTION_ID': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
        'AZURE_CLIENT_ID': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
        'AZURE_CLIENT_SECRET': 'your-client-secret',
        'AZURE_TENANT_ID': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
    },
    ssh_key='ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQC2...'
)
proxy = manager.get_proxy()
try:
    # Use the proxy
    pass
finally:
    proxy.close()
classmethod from_config(config: AzureConfig | None = None, runtime_config: ManagerRuntimeConfig | None = None) ProxyManagerAzure[source]

Create a ProxyManagerAzure instance from an AzureConfig object and a ManagerRuntimeConfig.

get_proxy(port: int = 0, size: Literal['small', 'medium', 'large'] = 'medium', region: str = '', auth: dict[Literal['user', 'password'], str] = {}, allowed_ips: str | list[str] = [], is_async: bool = False, retry: bool = True, proxy_name: str = '', on_exit: Literal['keep', 'destroy'] = 'destroy') AzureProxy[source]

Create and start an Azure-based proxy instance.

The method selects (or validates) a region, prepares authentication and allowed source IPs, starts the proxy VM/resources, and returns an AzureProxy wrapper.

Parameters:
  • port (int, optional) – TCP port for the proxy. If 0, a random port between 10000 and 65000 is selected. Defaults to 0.

  • size ({'small', 'medium', 'large'}, optional) – Proxy VM size profile. Defaults to 'medium'.

  • region (str, optional) – Preferred Azure region. If empty, a random region is selected from available regions for the selected size. Defaults to ''.

  • auth (dict, optional) – Basic-auth credentials as {'user': ..., 'password': ...}. If empty, no basic authentication is configured. Defaults to an empty dict.

  • allowed_ips (str or list[str], optional) – Source IP/range(s) allowed to access the proxy. Can be a single string or a list. The caller public IP is automatically added if missing. Defaults to an empty list.

  • is_async (bool, optional) – If True, do not wait for full VM startup before returning. Defaults to False.

  • retry (bool, optional) – Enable retry when startup fails and region was chosen randomly. Ignored when a specific region is provided. Defaults to True.

  • proxy_name (str, optional) – Explicit proxy name. If empty, a unique name of the form proxyN is generated. Defaults to ''.

  • on_exit ({'keep', 'destroy'}, optional) – Behavior when the returned proxy is closed. 'destroy' removes cloud resources; 'keep' leaves them running. Defaults to 'destroy'.

Returns:

Proxy wrapper object for the created Azure proxy.

Return type:

AzureProxy

Raises:
  • NameError – If proxy_name is provided and already exists.

  • ValueError – If region is provided but not available.

  • TypeError – If auth is not a dict, or if allowed_ips has an invalid IP/range format.

  • KeyError – If auth is provided without both 'user' and 'password' keys.

  • Exception – If proxy startup fails and no valid retry path remains.

get_proxy_by_name(name: str, is_async: bool = False, on_exit: Literal['destroy', 'keep'] = 'destroy') AzureProxy[source]

Reload an existing Azure proxy instance by its name.

The method validates that the proxy exists, retrieves VM metadata and public IP information, reads the remote Squid configuration to recover proxy settings (port, allowed IPs and optional basic-auth credentials), and returns a reloaded AzureProxy object.

Parameters:
  • name (str) – Name of the Azure proxy to load.

  • is_async (bool, optional) – If True, the returned proxy object uses asynchronous behavior for lifecycle operations. Defaults to False.

  • on_exit ({'destroy', 'keep'}, optional) – Behavior when the returned proxy is closed. 'destroy' removes resources and 'keep' leaves them running. Defaults to 'destroy'.

Returns:

Reloaded proxy instance bound to the existing Azure resources.

Return type:

AzureProxy

Raises:
  • NameError – If no running proxy with name exists.

  • Exception – If the public IP cannot be obtained.

  • ConnectionError – If the Squid configuration cannot be read through SSH.

  • ValueError – If the proxy port or VM size cannot be extracted from the instance data.

get_running_proxy_names() list[str][source]

Get list of running proxy names

auto_proxy_vpn.providers.azure.azure_utils.get_last_avaliable_sku_version(compute_client, publisher: str, offer: str, sku: str, location: str) str[source]

Return the latest available VM image version for a given Azure image SKU.

Parameters:
  • compute_client – Azure Compute management client with access to virtual_machine_images.list.

  • publisher (str) – Image publisher (for example 'Canonical').

  • offer (str) – Image offer name.

  • sku (str) – Image SKU name.

  • location (str) – Azure region used to query available versions.

Returns:

Version name considered the latest after descending sort.

Return type:

str

Raises:

Exception – Propagates errors raised by the Azure SDK request.

auto_proxy_vpn.providers.azure.azure_utils.start_proxy(manager: ProxyManagerAzure, proxy_name: str, port: int, region: str, machine_type: str, allowed_ips: list[str], user: str = '', password: str = '', is_async: bool = False) tuple[str, bool][source]

Create and start an Azure VM configured as an HTTP proxy.

This helper provisions all required Azure resources for a proxy VM, including a resource group, network security group, virtual network, public IP, network interface, and the virtual machine itself. The VM is initialized with a Squid startup script (cloud-init custom data) generated from the provided proxy settings.

Parameters:
  • manager (ProxyManagerAzure) – Manager instance that provides Azure SDK clients, model classes, image information, and SSH keys.

  • proxy_name (str) – Base name used for the VM and related Azure resources (resource group, NSG, VNet, NIC, etc.).

  • port (int) – TCP port exposed by the proxy service.

  • region (str) – Azure region where resources are created.

  • machine_type (str) – Azure VM size (for example 'Standard_B1s').

  • allowed_ips (list[str]) – Source IPs/ranges allowed to access SSH and proxy ports in inbound NSG rules.

  • user (str, optional) – Basic-auth username embedded in Squid configuration. Defaults to ''.

  • password (str, optional) – Basic-auth password embedded in Squid configuration. Defaults to ''.

  • is_async (bool, optional) – If True, return without waiting for VM creation completion. Defaults to False.

Returns:

A tuple (public_ip, error) where public_ip is the assigned IPv4 address (or '' when unavailable) and error indicates whether provisioning failed to produce a usable public IP.

Return type:

tuple[str, bool]

Raises:

Exception – Propagates exceptions raised by Azure SDK operations during resource creation and VM provisioning.

DigitalOcean

class auto_proxy_vpn.providers.digitalocean.digitalocean_proxy.DigitalOceanProxy(id: int, name: str, ip: str, port: int, region: str, token: str, active: bool = False, is_async: bool = False, user: str = '', password: str = '', logger: Logger | None = None, reload: bool = False, on_exit: Literal['keep', 'destroy'] = 'destroy')[source]

Bases: BaseProxy

__init__(id: int, name: str, ip: str, port: int, region: str, token: str, active: bool = False, is_async: bool = False, user: str = '', password: str = '', logger: Logger | None = None, reload: bool = False, on_exit: Literal['keep', 'destroy'] = 'destroy')[source]

Represent a DigitalOcean droplet-based proxy instance.

This object stores proxy metadata and lifecycle state, and can be initialized either for a newly created droplet or by reloading an existing one.

Parameters:
  • id (int) – DigitalOcean droplet ID.

  • name (str) – Droplet name.

  • ip (str) – Public IP address of the droplet. Can be empty while the droplet is still provisioning.

  • port (int) – Proxy listening port.

  • region (str) – Region slug where the droplet is deployed.

  • token (str) – DigitalOcean API token used for management requests.

  • active (bool, optional) – Whether the droplet is already active on DigitalOcean at initialization time. Defaults to False.

  • is_async (bool, optional) – If True, do not wait for full startup before returning. Defaults to False.

  • user (str, optional) – Basic-auth username configured for the proxy. Defaults to ''.

  • password (str, optional) – Basic-auth password configured for the proxy. Defaults to ''.

  • logger (logging.Logger or None, optional) – Logger used for status and lifecycle messages. Defaults to None.

  • reload (bool, optional) – If True, treat this instance as already initialized and skip startup activation checks. Defaults to False.

  • on_exit ({'keep', 'destroy'}, optional) – Behavior when the proxy is closed: keep the droplet or destroy it. Defaults to 'destroy'.

Raises:

ValueError – If on_exit is not 'keep' or 'destroy'.

is_active(wait: bool = False) bool[source]

Checks if proxy is active.

Parameters:

wait (bool) – Always wait until the proxy is active, even if it is asynchronous.

class auto_proxy_vpn.providers.digitalocean.digitalocean_proxy.ProxyManagerDigitalOcean(ssh_key: list[dict[str, str] | str] | dict[str, str] | str, project_name: str = 'AutoProxyVPN', project_description: str = 'On demand proxies', token: str = '', log: bool = True, log_file: str | None = None, log_format: str = '%(asctime)-10s %(levelname)-5s %(message)s', logger: Logger | None = None)[source]

Bases: BaseProxyManager[DigitalOceanProxy]

__init__(ssh_key: list[dict[str, str] | str] | dict[str, str] | str, project_name: str = 'AutoProxyVPN', project_description: str = 'On demand proxies', token: str = '', log: bool = True, log_file: str | None = None, log_format: str = '%(asctime)-10s %(levelname)-5s %(message)s', logger: Logger | None = None)[source]

Create a manager that provisions DigitalOcean proxy droplets on demand.

The manager validates API access, loads available regions and sizes, ensures a target project exists, and registers/creates SSH keys for newly created droplets.

Parameters:
  • ssh_key (list[dict[str, str] | str] | dict[str, str] | str) – SSH key configuration used for new droplets. Accepted forms are a single public key string, a dict with {'name': ..., 'public_key': ...}, a list mixing both forms, or a file path containing one public key per line.

  • project_name (str, optional) – Name of the DigitalOcean project used to group managed proxies. Defaults to 'AutoProxyVPN'.

  • project_description (str, optional) – Description for the DigitalOcean project if it needs to be created. Defaults to 'On demand proxies'.

  • token (str, optional) – DigitalOcean API token. If empty, the value is read from the DIGITALOCEAN_API_TOKEN environment variable. Defaults to ''.

  • log (bool, optional) – Enable logging for manager actions. Defaults to True.

  • log_file (str or None, optional) – File path for logging output. If None, logs are emitted to the terminal. Defaults to None.

  • log_format (str, optional) – Format string used by logging when an internal logger is created. Defaults to '%(asctime)-10s %(levelname)-5s %(message)s'.

  • logger (logging.Logger or None, optional) – Custom logger instance. When provided, log_file and log_format are ignored. Defaults to None.

Raises:

Examples

Use environment token with a context manager:

proxy_manager = ProxyManagerDigitalOcean(
    ssh_key='dummy existing key'
)
with proxy_manager.get_proxy() as proxy:
    result = requests.get('https://google.com', proxies=proxy.get_proxy())

Pass token explicitly and close manually:

proxy_manager = ProxyManagerDigitalOcean(
    ssh_key={'name': 'dummy_key', 'public_key': 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQC2...'},
    token='dop_v1_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
)
proxy = proxy_manager.get_proxy()
try:
    # Use the proxy
    pass
finally:
    proxy.close()
classmethod from_config(config: DigitalOceanConfig | None = None, runtime_config: ManagerRuntimeConfig | None = None) ProxyManagerDigitalOcean[source]

Create a ProxyManagerDigitalOcean instance from a DigitalOceanConfig object and a ManagerRuntimeConfig.

get_proxy(port: int = 0, size: Literal['small', 'medium', 'large'] = 'medium', region: str = '', auth: dict[Literal['user', 'password'], str] = {}, allowed_ips: str | list[str] = [], is_async: bool = False, retry: bool = True, proxy_name: str = '', on_exit: Literal['keep', 'destroy'] = 'destroy') DigitalOceanProxy[source]

Starts a new proxy in DigitalOcean with the given settings and returns a proxy object to manage it.

Parameters:
  • port (int, optional) – Port number for the proxy. Default: random port between 10000 and 65000.

  • size ({'small', 'medium', 'large'}, optional) – Size of the server to deploy. Small size has fewer regions. Defaults to 'medium'.

  • region (str, optional) – Region to start the proxy on. Starts on a random region if empty. To get available regions by size call get_regions_by_size().

  • auth (dict, optional) – Basic auth for the proxy. Example: {'user': 'test', 'password': 'test01'}

  • allowed_ips (str or list[str], optional) – Allowed IP addresses or CIDR ranges. If empty, the current public IP address is used by default. A single IP may be provided as a string. Example: '8.8.8.8', ['127.0.0.0/8', '1.1.1.1']

  • is_async (bool, optional) – If True, returns without waiting for the proxy to be active.

  • retry (bool, optional) – If True, retries in another region if the first isn’t available. Always False when region is given.

  • proxy_name (str, optional) – Name of the created proxy. By default proxy1, proxy2, etc.

  • on_exit ({'keep', 'destroy'}, optional) – When the proxy is closed, 'destroy' permanently removes it; otherwise it stays running and can be retrieved later with get_proxy_by_name.

Returns:

DigitalOceanProxy instance containing the new created proxy.

Return type:

DigitalOceanProxy

get_proxy_by_name(name: str, is_async: bool = False, on_exit: Literal['destroy', 'keep'] = 'destroy') DigitalOceanProxy[source]

Gets a proxy instance by droplet name.

Parameters:
  • name (str) – Droplet name.

  • is_async (bool, optional) – If True, the returned proxy uses asynchronous behavior for lifecycle operations. Defaults to False.

  • on_exit ({'keep', 'destroy'}, optional) – Keep or destroy the proxy when the program ends. Defaults to 'destroy'.

Returns:

DigitalOceanProxy instance of the proxy.

Return type:

DigitalOceanProxy

Raises:
get_running_proxy_names() list[str][source]

Get list of running proxy names

auto_proxy_vpn.providers.digitalocean.digitalocean_utils.get_or_create_project(name: str, description: str, headers: dict[str, str]) str[source]

Creates the project if doesn’t exist and sets the project as default. Returns the project id.

auto_proxy_vpn.providers.digitalocean.digitalocean_utils.get_or_create_ssh_keys(ssh_keys: list[dict[str, str] | str] | dict[str, str] | str, headers: dict[str, str]) list[int][source]

Gets or creates ssh keys in DigitalOcean. If no ssh key then a dummy one will be created.

auto_proxy_vpn.providers.digitalocean.digitalocean_utils.get_servers_and_size(server_size: str, active_servers: list[dict], servers: list[str], vpn: bool = False) Tuple[str, list[str]][source]

Get the server size slug and the list of servers that support it

auto_proxy_vpn.providers.digitalocean.digitalocean_utils.get_next_droplet_name(headers: dict[str, str], name: str = '', is_vpn: bool = False) str[source]

Get next avaliable proxy or vpn name.

auto_proxy_vpn.providers.digitalocean.digitalocean_utils.start_proxy(name: str, image: str, region: str, size: str, port: int, ssh_keys: list[str], headers: dict[str, str], regions: list[str], logger: Logger | None, allowed_ips: list[str] = [], user: str = '', password: str = '', is_async: bool = False, retry: bool = True) Tuple[int, str, bool][source]

Create a DigitalOcean droplet configured as an HTTP proxy.

The function provisions a droplet with a Squid startup script, optionally retries in alternative regions when capacity errors occur (HTTP 422), and returns the droplet id, detected public IP, and an error flag.

Parameters:
  • name (str) – Droplet name.

  • image (str) – DigitalOcean image slug used to create the droplet.

  • region (str) – Preferred region slug.

  • size (str) – Droplet size slug.

  • port (int) – Proxy port used in Squid configuration.

  • ssh_keys (list[str]) – List of SSH keys.

  • headers (dict[str, str]) – Request headers including API authorization.

  • regions (list[str]) – Candidate region list used for fallback retries. This list may be modified in place when a region is discarded.

  • logger (Logger or None) – Optional logger used for status/warning messages.

  • allowed_ips (list[str], optional) – Source IPs/ranges allowed by Squid. Defaults to an empty list.

  • user (str, optional) – Basic-auth username configured in Squid. Defaults to ''.

  • password (str, optional) – Basic-auth password configured in Squid. Defaults to ''.

  • is_async (bool, optional) – If True, do not wait for droplet activation before returning. Defaults to False.

  • retry (bool, optional) – If True, retry in other available regions when region capacity is unavailable. Defaults to True.

Returns:

A tuple (droplet_id, public_ip, error) where error indicates whether startup/IP resolution failed.

Return type:

tuple[int, str, bool]

Raises:

CountryNotAvailableException – If no suitable region is available and retry is False (or no fallback remains).

exception auto_proxy_vpn.providers.digitalocean.digitalocean_exceptions.DropletNotProxyException(*args)[source]

Bases: Exception