/[marcuscom]/meraki/setup_meraki_nets.py
ViewVC logotype

Contents of /meraki/setup_meraki_nets.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 20552 - (show annotations) (download) (as text)
Tue May 8 03:22:24 2018 UTC (23 months ago) by jclarke
File MIME type: text/x-python
File size: 12481 byte(s)
Check to make sure a network has devices.

1 #!/usr/bin/env python
2 #
3 # Copyright (c) 2018 Joe Clarke <jclarke@cisco.com>
4 #
5 # Redistribution and use in source and binary forms, with or without
6 # modification, are permitted provided that the following conditions
7 # are met:
8 # 1. Redistributions of source code must retain the above copyright
9 # notice, this list of conditions and the following disclaimer.
10 # 2. Redistributions in binary form must reproduce the above copyright
11 # notice, this list of conditions and the following disclaimer in the
12 # documentation and/or other materials provided with the distribution.
13 #
14 # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24 # SUCH DAMAGE.
25
26
27 import meraki_api
28 import yaml
29 import argparse
30 import sys
31 import os
32
33
34 def main():
35 parser = argparse.ArgumentParser(
36 prog=sys.argv[0], description='Add devices to network')
37 parser.add_argument('--config', '-c', metavar='<CONFIG FILE>',
38 help='Path to the organization configuration file', required=True)
39 parser.add_argument(
40 '--networks', '-n', metavar='<NETWORK>[,<NETWORK>[,...]]', help='Comma-separated list of networks to process')
41 args = parser.parse_args()
42
43 if not os.path.isfile(args.config):
44 print('Config file {} does not exist or is not a file!'.format(args.config))
45 sys.exit(1)
46
47 with open(args.config, 'r') as c:
48 config = yaml.load(c)
49
50 for key in ['api_key', 'organization', 'networks']:
51 if not key in config:
52 print('Invalid config: {} is missing!'.format(key))
53 sys.exit(1)
54
55 meraki = meraki_api.Meraki(key=config['api_key'])
56 orgs = meraki.get_organizations()
57 org = None
58 for o in orgs:
59 if o.get('name') == config['organization']:
60 org = o
61 break
62
63 if org is None:
64 print('Failed to find organization {} in this profile!'.format(
65 config['organization']))
66 sys.exit(1)
67
68 nets = org.get_networks()
69 inv = org.get_inventory()
70
71 errors = 0
72
73 configure_nets = None
74 if args.networks is not None:
75 configure_nets = args.networks.split(',')
76
77 for net in config['networks']:
78 nerrors = 0
79 net_obj = None
80 nname = net.keys()[0]
81 if configure_nets is not None and nname not in configure_nets:
82 continue
83
84 validn = True
85 for key in ['address', 'timezone']:
86 if key not in net[nname]:
87 print('Invalid network config for {}: {} is missing!'.format(nname, key))
88 errors += 1
89 validn = False
90 break
91
92 if not validn:
93 continue
94
95 for n in nets:
96 if n.get('name') == nname:
97 net_obj = n
98 break
99
100 if net_obj is None:
101 net_obj = org.create_network(
102 nname, timezone=net[nname]['timezone'])
103
104 if net_obj is None:
105 print('Error creating new network {}!'.format(nname))
106 errors += 1
107 continue
108
109 if 'devices' in net[nname]:
110 for dev in net[nname]['devices']:
111 serial = dev.keys()[0]
112 if 'name' not in dev[serial]:
113 print('Invalid device {}: name is missing!'.format(serial))
114 nerrors += 1
115 continue
116
117 inv_dev = filter(lambda device: device['serial'] == serial, inv)
118 if len(inv_dev) == 1:
119 dev_obj = None
120 if inv_dev[0]['networkId'] is not None and inv_dev[0]['networkId'] != net_obj.get('id'):
121 try:
122 inv_net_obj = meraki_api.Network(
123 key=config['api_key'], id=inv_dev[0]['networkId'])
124 dev_obj = meraki_api.Device(
125 key=config['api_key'], id=inv_dev[0]['serial'], net=inv_net_obj)
126
127 res = dev_obj.remove_device()
128 if not res:
129 nerrors += 1
130 continue
131 res = net_obj.claim_device(dev_obj)
132 if not res:
133 nerrors += 1
134 continue
135 except Exception as e:
136 print('Error updating device network membership for {}: {}'.format(
137 inv_dev[0]['serial'], e))
138 nerrors += 1
139 continue
140 elif inv_dev[0]['networkId'] is None:
141 try:
142 dev_obj = meraki_api.Device(
143 key=config['api_key'], id=inv_dev[0]['serial'], net=net_obj)
144 res = net_obj.claim_device(dev_obj)
145 if not res:
146 nerrors += 1
147 continue
148 except Exception as e:
149 print('Error claiming device {}: {}'.format(
150 inv_dev[0]['serial'], e))
151 nerrors += 1
152 continue
153
154 else:
155 dev_obj = meraki_api.Device(
156 key=config['api_key'], id=inv_dev[0]['serial'], net=net_obj)
157
158 dev_location = net[nname]['address']
159 dev_name = dev[serial]['name']
160 if 'location' in dev[serial]:
161 dev_location += '\n' + dev[serial]['location']
162 dev_obj.update_device(
163 name=dev_name, address=dev_location, moveMapMarker=True)
164
165 else:
166 print('Error finding {} in inventory!'.format(serial))
167 nerrors += 1
168
169 if 'vlans' in net[nname]:
170 print('\n')
171 # Ugh. There is no API to enable VLANs yet. So it's best to
172 # make this a manual step. We could interact over the web, but
173 # then we'd need to ask for a real user's credentials.
174 raw_input(
175 '!!! Enable VLANs for network "{}" manually in the dashboard (under Security appliance > Addressing & VLANs), then hit enter to proceed !!!'.format(nname))
176 print('')
177 for vlan in net[nname]['vlans']:
178 vname = vlan.keys()[0]
179 if int(vlan[vname]['id']) != 1:
180 vlan_obj = net_obj.create_vlan(
181 vname, vlan[vname]['id'], vlan[vname]['subnet'], vlan[vname]['appliance_ip'])
182 else:
183 vlan_obj = meraki_api.Vlan(
184 key=config['api_key'], id=1, net=net_obj)
185 if vlan_obj is None:
186 nerrors += 1
187 continue
188 vargs = {}
189 for key in ['reserved_ip_ranges', 'fixed_ip_assignments', 'dns_nameservers']:
190 if key in vlan[vname]:
191 vargs[key] = vlan[vname][key]
192 res = vlan_obj.update_vlan(**vargs)
193 if not res:
194 nerrors += 1
195
196 if 'ssids' in net[nname]:
197 if len(net[nname]['ssids']) > 4:
198 print('Only four SSIDs are allowed per network!')
199 nerrors += 1
200 else:
201 si = 0
202 for ssid in net[nname]['ssids']:
203 sname = ssid.keys()[0]
204 ssid_obj = meraki_api.SSID(
205 key=config['api_key'], id=si, name=sname, net=net_obj)
206 sargs = {}
207 for key in ['name', 'enabled', 'auth_mode', 'encryption_mode', 'psk', 'ip_assignment_mode']:
208 if key in ssid[sname]:
209 sargs[key] = ssid[sname][key]
210 res = ssid_obj.update_ssid(**sargs)
211 if not res:
212 nerrors += 1
213 si += 1
214
215 if 'switches' in net[nname]:
216 for switch in net[nname]['switches']:
217 serial = switch.keys()[0]
218 dev_obj = meraki_api.Device(
219 key=config['api_key'], id=serial, net=net_obj)
220 if not dev_obj.realize():
221 print('Device {} is not in network {}'.format(
222 serial, net_obj.get('name')))
223 nerrors += 1
224 continue
225
226 for switchport in switch[serial]:
227 port_range = switchport.keys()[0]
228 ports = []
229 if isinstance(port_range, (int, long)):
230 port_obj = meraki_api.SwitchPort(
231 key=config['api_key'], id=port_range, dev=dev_obj)
232 ports.append(port_obj)
233 else:
234 prs = port_range.split(',')
235 for pr in prs:
236 pr = pr.strip()
237 if isinstance(pr, (int, long)):
238 port_obj = meraki_api.SwitchPort(
239 key=config['api_key'], id=pr, dev=dev_obj)
240 ports.append(pr)
241 else:
242 if '-' not in pr:
243 print('Port range {} is invalid.'.format(pr))
244 nerrors += 1
245 continue
246
247 (start, end) = pr.split('-')
248 start = start.strip()
249 end = end.strip()
250 if not isinstance(start, (int, long)) or not isinstance(end, (int, long)):
251 print('Error with port range {} and {} must be integers'.format(
252 pr, start, end))
253 nerrors += 1
254 continue
255
256 if start >= end:
257 print(
258 'Error with port range {}; start must be less than end'.format(pr))
259 nerrors += 1
260 continue
261
262 pi = start
263 while pi <= end:
264 port_obj = meraki_api.SwitchPort(
265 key=config['api_key'], id=pi, dev=dev_obj)
266 ports.append(port_obj)
267 pi += 1
268
269 for port in ports:
270 pargs = {}
271 for key in ['name', 'tags', 'enabled', 'type', 'vlan', 'voice_vlan', 'allowed_vlans', 'poe_enabled']:
272 if key in switchport[port_range]:
273 pargs[key] = switchport[port_range][key]
274 res = port.update_switchport(**pargs)
275 if not res:
276 nerrors += 1
277
278 if nerrors == 0:
279 print('Network {} has been setup successfully!'.format(nname))
280 else:
281 print(
282 'Error fully configuring network {}. See the errors above for more details.'.format(nname))
283 errors += nerrors
284
285 if errors == 0:
286 print('All networks have been setup successfully!')
287 else:
288 print('There were errors setting up some of the networks. See the output above for more details.')
289 sys.exit(1)
290
291
292 if __name__ == '__main__':
293 main()

Properties

Name Value
svn:executable *

  ViewVC Help
Powered by ViewVC 1.1.27