-
-
Save cryzed/5303f2e4ec1b4125f30fd31662d5b1be to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import os | |
import socket | |
import subprocess | |
# The list of fallbacks might have to be extended for operating systems that | |
# aren't Arch Linux. | |
IP_PATHS = '/usr/bin/ip', | |
def collect_environment_variables(name_format): | |
index = 1 | |
collected = [] | |
while True: | |
value = os.environ.get(name_format % index, None) | |
if value is None: | |
return collected | |
collected.append(value) | |
index += 1 | |
def get_fallback_path(paths): | |
for path in paths: | |
if os.path.exists(path): | |
return path | |
def main(): | |
script_type = os.environ['script_type'] | |
if script_type not in ('up', 'down'): | |
return | |
ip = get_fallback_path(IP_PATHS) | |
action = 'add' if script_type == 'up' else 'del' | |
route_net_gateway = os.environ['route_net_gateway'] | |
for remote in collect_environment_variables('remote_%d'): | |
for address in set(i[4][0] for i in socket.getaddrinfo(remote, None)): | |
# Ignore return code to not raise an error when we attempt to add | |
# the already existing route | |
subprocess.run((ip, 'route', action, address, 'via', route_net_gateway)) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment