-
Notifications
You must be signed in to change notification settings - Fork 1
/
merakiumbrella
executable file
·298 lines (245 loc) · 9.66 KB
/
merakiumbrella
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
#!/usr/bin/env python3
#
# Update Umbrella Networks based on Meraki Networks
#
# Meraki support must whitelist the public IP from where this script is run,
# as well as the account used to perform the update.
#
#
# dyndns2 format::
#
# curl -v -u [email protected] 'https://updates.opendns.com/nic/update?hostname=Net%20name&origin_ip=xx.xx.xx.xx'
#
# Spaces in hostname need to be replaced with %20
# Use %40 in username to replace @
#
#
# Use base64 to encode the Umbrella password.
#
# unset HISTFILE && echo -n secretPass | base64
#
# Format of YAML configuration file is as such:
#
# apikey: 'your-api-key-goes-here'
#
# username: '[email protected]'
# password64: 'c2VjcmV0UGFzcw=='
#
# networks:
# - meraki: 'Network1'
# umbrella: 'Network 1'
# - meraki: 'Another Net'
# umbrella: 'Another Network'
#
import base64
import getopt
import os
import sys
import requests
import yaml
import meraki
DEFAULT_CONFIG_NAME = 'merakiumbrella.yaml'
class MerakiUmbrella:
"""Use Meraki network details to update Umbrella
"""
def __init__(self, verbose=False):
self.configuration = {}
self.verbose = verbose
self.debug = False
self.apikey = ''
self.orgid = ''
self.dashboard = None
self.configfile = DEFAULT_CONFIG_NAME
def get_dashboard(self):
"""Create the dashboard API object
"""
try:
self.dashboard = meraki.DashboardAPI(api_key=self.apikey,
output_log=self.debug,
print_console=self.debug,
suppress_logging=True)
except meraki.exceptions.APIKeyError as exception:
print(f"Error: {exception}")
sys.exit(5)
def get_organization(self) -> dict:
"""Get the organization object.
If there are more than one organizations accessible by the apikey,
then the configuration must specify which one to use.
Returns:
dict: [description]
"""
try:
organizations = self.dashboard.organizations.getOrganizations()
except meraki.exceptions.APIError as exception:
print(f"Error: Unable to get organizations: {exception}")
return None
if not organizations:
print("Error: No organizations found")
return None
# print("len(organizations) == {}".format(len(organizations)))
if len(organizations) > 1:
org_id = None
if 'meraki' in self.configuration and 'org_id' in self.configuration['meraki']:
org_id = self.configuration['meraki']['org_id']
for organization in organizations:
if self.verbose:
#print("org={}".format(organizations))
print("Organization: {} {}".format(organization['id'], organization['name']))
if org_id == organization['id']:
return organization
if self.orgid == organization['id']:
return organization
if not org_id:
print("Error: more than one organization available, but none specified")
else:
print(f"Error: org_id not found: {org_id}")
sys.exit(9)
return organizations[0]
def get_networks(self):
"""Get the Meraki networks
"""
organization = self.get_organization()
try:
networks = self.dashboard.organizations.getOrganizationNetworks(organization['id'])
except meraki.exceptions.APIError as exception:
print(f"Error: Unable to get networks: {exception}")
return None
return networks
def doDynDns2(username, password, hostname, myip):
"""Perform a dynamic update
Args:
username ([type]): [description]
password ([type]): [description]
hostname ([type]): [description]
myip ([type]): [description]
"""
url = 'https://updates.opendns.com/nic/update?hostname={}&origin_ip={}'.format(hostname.replace(" ","%20"), myip)
if self.verbose:
print(f"url={url}")
headers = {}
# headers['X-Cisco-Meraki-API-Key'] = key
try:
r = requests.get(url, headers=headers, auth=(username, password))
except requests.exceptions.RequestException as e:
print("Error: %s" % (e))
return False
except KeyboardInterrupt:
print("Aborted")
sys.exit(25)
if self.verbose:
print("r.status_code = %s" % (r.status_code))
print("r.text = %s" % (r.text))
if r.status_code == 400:
if self.verbose:
print("400 Bad request: %s : %s" % (url, r.text))
return False
if r.status_code == 401:
print("Bad auth ({}): {}".format(username,url))
sys.exit(50)
if r.status_code == 404:
print("404 Not found: %s" % (url))
return False
if r.status_code != 200:
print("Error: %s - %s" % (r.status_code, r.text))
return False
if r.text.startswith("good"):
print("{} updated to {}".format(hostname, myip))
return True
elif r.text == "nohost":
print("{} Umbrella network does not exist. Or account/source IP not authorized.".format(hostname))
return False
def get_config(self):
"""Get config from configuration file
"""
if not os.path.isfile(self.configfile):
print("Config file missing: {}".format(self.configfile))
sys.exit(3)
with open(self.configfile) as fp:
self.configuration = yaml.load(fp, Loader=yaml.SafeLoader)
if self.verbose:
print("configuration={}".format(self.configuration))
if 'apikey' in self.configuration:
self.apikey = self.configuration['apikey']
if len(self.apikey) < 1:
print("Missing apikey")
sys.exit(1)
if not 'networks' in self.configuration:
print("Missing 'networks' in configuration")
sys.exit(20)
if not 'umbrella' in self.configuration:
print("Missing 'umbrella' in configuration")
sys.exit(21)
if not 'username' in self.configuration['umbrella']:
print("Missing 'username' in umbrella configuration")
sys.exit(21)
if ((not 'password' in self.configuration['umbrella']) and
(not 'password64' in self.configuration['umbrella'])):
print("Missing 'password' or 'password64' in configuration")
sys.exit(22)
def get_umbrella_password(self) -> str:
"""Get the Umbrella password from configuration
"""
if 'password' in self.configuration['umbrella']:
return self.configuration['umbrella']['password']
if 'password64' in self.configuration['umbrella']:
return base64.b64decode(self.configuration['umbrella']['password64'])
return None
def main(self):
"""
Parse the command line and configuration.
"""
if 'MERAKI_APIKEY' in os.environ:
self.apikey = os.environ['MERAKI_APIKEY']
if 'MERAKI_ORGID' in os.environ:
self.orgid = os.environ['MERAKI_ORGID']
options = getopt.getopt(sys.argv[1:], 'a:c:o:v', [ 'apikey=', 'config=', 'orgid='
'verbose',
])[0]
for opt, arg in options:
if opt in ('-v', '--verbose'):
self.verbose = True
elif opt in ('-a', '--apikey'):
self.apikey = arg
elif opt in ('-c', '--config'):
self.configfile = arg
elif opt in ('-o', '--orgid'):
self.orgid = arg
if len(self.configfile) < 1:
print("Missing config filename")
sys.exit(2)
self.get_config()
self.get_dashboard()
org = self.get_organization()
# print(f'org={org}')
uplinks = self.dashboard.appliance.getOrganizationApplianceUplinkStatuses(org['id'])
# print(f'uplinks={uplinks}')
uplinks_by_network_id = {}
for uplink in uplinks:
uplinks_by_network_id[uplink['networkId']] = uplink
networks = self.get_networks()
#for network in networks:
# print(f"{network}")
networksByName = {}
networks_by_id = {}
for network in networks:
networksByName[network['name']] = network
networks_by_id[network['id']] = network
password = self.get_umbrella_password()
for network in self.configuration['networks']:
if self.verbose:
print(f"network={network}")
print("meraki={}".format(network['meraki']))
if not network['meraki'] in networksByName:
print("{} is not a known Meraki network".format(network['meraki']))
sys.exit(30)
app_uplink = uplinks_by_network_id[networksByName[network['meraki']]['id']]
print(f'app_uplink={app_uplink}')
for uplink in app_uplink['uplinks']:
print(f'uplink={uplink}')
if uplink['status'] == 'active':
if self.verbose:
print("publicIp={}".format(uplink['publicIp']))
#self.doDynDns2(self.configuration['username'], password, network['umbrella'], uplink['publicIp'])
sys.exit(0)
if __name__ == "__main__":
MerakiUmbrella().main()