Skip to content

Instantly share code, notes, and snippets.

@kfoxton
Forked from cdodd/parse-o365-ip-addrs.py
Created March 15, 2018 20:37
Show Gist options
  • Save kfoxton/e5bdfd2a5592af2f8c9c1dff91b06178 to your computer and use it in GitHub Desktop.
Save kfoxton/e5bdfd2a5592af2f8c9c1dff91b06178 to your computer and use it in GitHub Desktop.
Parse and reformat the IP address ranges for various Office 365 services.
#!/usr/bin/env python
import xmltodict
from socket import inet_ntoa
from struct import pack
import sys
import urllib
def calcDottedNetmask(mask):
bits = 0xffffffff ^ (1 << 32 - mask) - 1
return inet_ntoa(pack('>I', bits))
# Read from URL
data = urllib.urlopen('https://support.content.office.net/en-us/static/O365IPAddresses.xml').read()
doc = xmltodict.parse(data)
# Read from local file
# doc = xmltodict.parse(open('/path/to/file.xml').read())
for x in doc['products']['product']:
if x['@name'] in ['o365', 'Identity', 'SPO', 'LYO', 'Yammer', 'OneNote']:
print '#' * (len(x['@name']) + 2)
print '# ' + x['@name']
print '#' * (len(x['@name']) + 2)
for y in x['addresslist']:
if y['@type'] == 'IPv4':
for ip in y['address']:
if '/' not in ip:
ip, dot_mask = (ip, '255.255.255.255')
else:
ip, cidr_mask = ip.split('/')
dot_mask = calcDottedNetmask(int(cidr_mask))
print 'route inside ' + ip + ' ' + dot_mask + ' ' + sys.argv[1]
print
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment