Toggle VPN Mock Network Manager Script in Python

Simulate a VPN manager with connect, disconnect, toggle, and status methods for testing or demo workflows.

Easy Python 3.9+ Aug 9, 2026 Automation & scripting 11 views 0 copies

Python code

41 lines
Python 3.9+
import time

class MockVPNManager:
    def __init__(self):
        self.is_connected = False
        self.servers = ["us-west", "eu-central", "asia-east"]
        self.active_server = None

    def toggle(self):
        if self.is_connected:
            self.disconnect()
        else:
            self.connect()

    def connect(self):
        self.is_connected = True
        self.active_server = self.servers[(len(time.ctime()) % 3)]
        print(f"VPN connected to {self.active_server}")

    def disconnect(self):
        self.is_connected = False
        print(f"VPN disconnected from {self.active_server}")
        self.active_server = None

    def status(self):
        if self.is_connected:
            print(f"Status: Connected to {self.active_server}")
        else:
            print("Status: Disconnected")


def main():
    vpn = MockVPNManager()
    vpn.status()
    vpn.toggle()
    vpn.toggle()
    vpn.status()


if __name__ == "__main__":
    main()

Output

stdout
Status: Disconnected
VPN connected to us-west
VPN disconnected from us-west
Status: Disconnected

How it works

The MockVPNManager class tracks connection state with the is_connected attribute and picks a server from a list. The toggle method flips the state by calling either connect or disconnect, making the logic easy to reuse in loops or automated tests. Using len(time.ctime()) % 3 rotates servers pseudo-randomly, giving each run a different server without needing the random module. Since all state is stored on the instance, you can create multiple managers in one process for parallel simulations.

Common mistakes

  • Calling `toggle` without checking if a server is already active can double-connect or leave stale state
  • Assuming `active_server` stays set after disconnect when it is reset to None
  • Typing `time` without importing the module first

Variations

  1. Use a `random.choice(self.servers)` import for truly random server selection
  2. Add a `sleep` duration in `connect` to simulate network latency

Real-world use cases

  • Simulating VPN behavior in a CI pipeline to test network-dependent deploys without a real VPN.
  • Driving a UI mock or hardware script where toggling connection state must happen on demand.
  • Teaching or demoing state-machine patterns in a scripted training environment.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.