Toggle VPN Mock Network Manager Script in Python
Simulate a VPN manager with connect, disconnect, toggle, and status methods for testing or demo workflows.
Python code
41 linesimport 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
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
- Use a `random.choice(self.servers)` import for truly random server selection
- 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
More from Automation & scripting
- Aggregate Log Errors Count by Hour in Python easy
- Automate Tweeting New Blog Posts in Python easy
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
Keep learning
Related tutorials and quizzes for this topic.