Guest User

Untitled

a guest
Jun 18th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.58 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. import argparse
  4. import dns.resolver
  5. import netifaces
  6.  
  7. from subprocess import call
  8.  
  9. def get_interface_by_ip(ip):
  10. """Given an IP will return the interface associated. Doesn't support the same IP bound to multiple interfaces.
  11.  
  12. Args:
  13. ip: The IP that belongs to a given interface
  14.  
  15. Returns:
  16. A string that represents a given interface
  17. """
  18. for interface in netifaces.interfaces():
  19. # Get the addresses of all interfaces
  20. addresses = netifaces.ifaddresses(interface)
  21.  
  22. # Check if the interface has an ipv4 address assigned to it
  23. if netifaces.AF_INET in addresses:
  24.  
  25. # Iterate through the ipv4s checking if peer matches next hop
  26. for ipv4 in addresses[netifaces.AF_INET]:
  27.  
  28. if 'peer' in ipv4 and ipv4['peer'] == ip:
  29. return interface
  30.  
  31. raise FileNotFoundError('Could not identify an interface with the IP "' + ip + '"')
  32.  
  33. def get_ips(domain):
  34. """ Given a domain, looks up the IP
  35. Args:
  36. domain: The domain that should be queried
  37.  
  38. Returns:
  39. A string IP value for the domain
  40. """
  41. result = dns.resolver.query(domain, 'A')
  42. ips = []
  43. for answer in result:
  44. ips.append(answer.to_text())
  45.  
  46. return ips
  47.  
  48. def get_args():
  49. """Renders and returns the arguments from the CLI
  50.  
  51. Returns:
  52. The namespace object containing arguments of the form:
  53.  
  54. {
  55. 'argument_name': 'argument_value'
  56. }
  57. """
  58. parser = argparse.ArgumentParser(description='Add a route for a given domain to a given interface. Only supports IPv4')
  59.  
  60. # Add the arguments
  61. parser.add_argument('--domain', dest='domain', action='store', required=True,
  62. help='The domain that you would like to route to via a given interface')
  63.  
  64. parser.add_argument('--next-hop', dest='next_hop', action='store', required=True,
  65. help='The next hop to route over')
  66.  
  67. return parser.parse_args()
  68.  
  69. def main():
  70.  
  71. args = get_args()
  72. ips = get_ips(args.domain)
  73. interface = get_interface_by_ip(args.next_hop)
  74.  
  75. for ip in ips:
  76. result = call(['ip', 'route', 'add',ip + '/32', 'via',args.next_hop,'dev',interface])
  77.  
  78. if result == 2:
  79. raise PermissionError('Unable to add the route: insufficient permissions')
  80. elif result > 0:
  81. raise Exception('Unable to add the route: exit code from "ip" nonzero (' + result + ')')
  82. else:
  83. print('Added route for "' + ip + '" via "' + args.next_hop + ' (' + interface + ')"')
  84.  
  85. if __name__ == "__main__":
  86. main()
Add Comment
Please, Sign In to add comment