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

Annotation of /meraki/setup_meraki_nets.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 20550 - (hide annotations) (download) (as text)
Mon May 7 21:11:26 2018 UTC (23 months ago) by jclarke
File MIME type: text/x-python
File size: 12233 byte(s)
Add the initial code drop for my Meraki setup system.

1 jclarke 20550 #!/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     for dev in net[nname]['devices']:
110     serial = dev.keys()[0]
111     if 'name' not in dev[serial]:
112     print('Invalid device {}: name is missing!'.format(serial))
113     nerrors += 1
114     continue
115    
116     inv_dev = filter(lambda device: device['serial'] == serial, inv)
117     if len(inv_dev) == 1:
118     dev_obj = None
119     if inv_dev[0]['networkId'] is not None and inv_dev[0]['networkId'] != net_obj.get('id'):
120     try:
121     inv_net_obj = meraki_api.Network(
122     key=config['api_key'], id=inv_dev[0]['networkId'])
123     dev_obj = meraki_api.Device(
124     key=config['api_key'], id=inv_dev[0]['serial'], net=inv_net_obj)
125    
126     res = dev_obj.remove_device()
127     if not res:
128     nerrors += 1
129     continue
130     res = net_obj.claim_device(dev_obj)
131     if not res:
132     nerrors += 1
133     continue
134     except Exception as e:
135     print('Error updating device network membership for {}: {}'.format(
136     inv_dev[0]['serial'], e))
137     nerrors += 1
138     continue
139     elif inv_dev[0]['networkId'] is None:
140     try:
141     dev_obj = meraki_api.Device(
142     key=config['api_key'], id=inv_dev[0]['serial'], net=net_obj)
143     res = net_obj.claim_device(dev_obj)
144     if not res:
145     nerrors += 1
146     continue
147     except Exception as e:
148     print('Error claiming device {}: {}'.format(
149     inv_dev[0]['serial'], e))
150     nerrors += 1
151     continue
152    
153     else:
154     dev_obj = meraki_api.Device(
155     key=config['api_key'], id=inv_dev[0]['serial'], net=net_obj)
156    
157     dev_location = net[nname]['address']
158     dev_name = dev[serial]['name']
159     if 'location' in dev[serial]:
160     dev_location += '\n' + dev[serial]['location']
161     dev_obj.update_device(
162     name=dev_name, address=dev_location, moveMapMarker=True)
163    
164     else:
165     print('Error finding {} in inventory!'.format(serial))
166     nerrors += 1
167    
168     if 'vlans' in net[nname]:
169     print('\n')
170     # Ugh. There is no API to enable VLANs yet. So it's best to
171     # make this a manual step. We could interact over the web, but
172     # then we'd need to ask for a real user's credentials.
173     raw_input(
174     '!!! Enable VLANs for network "{}" manually in the dashboard (under Security appliance > Addressing & VLANs), then hit enter to proceed !!!'.format(nname))
175     print('')
176     for vlan in net[nname]['vlans']:
177     vname = vlan.keys()[0]
178     if int(vlan[vname]['id']) != 1:
179     vlan_obj = net_obj.create_vlan(
180     vname, vlan[vname]['id'], vlan[vname]['subnet'], vlan[vname]['appliance_ip'])
181     else:
182     vlan_obj = meraki_api.Vlan(
183     key=config['api_key'], id=1, net=net_obj)
184     if vlan_obj is None:
185     nerrors += 1
186     continue
187     vargs = {}
188     for key in ['reserved_ip_ranges', 'fixed_ip_assignments', 'dns_nameservers']:
189     if key in vlan[vname]:
190     vargs[key] = vlan[vname][key]
191     res = vlan_obj.update_vlan(**vargs)
192     if not res:
193     nerrors += 1
194    
195     if 'ssids' in net[nname]:
196     if len(net[nname]['ssids']) > 4:
197     print('Only four SSIDs are allowed per network!')
198     nerrors += 1
199     else:
200     si = 0
201     for ssid in net[nname]['ssids']:
202     sname = ssid.keys()[0]
203     ssid_obj = meraki_api.SSID(
204     key=config['api_key'], id=si, name=sname, net=net_obj)
205     sargs = {}
206     for key in ['name', 'enabled', 'auth_mode', 'encryption_mode', 'psk', 'ip_assignment_mode']:
207     if key in ssid[sname]:
208     sargs[key] = ssid[sname][key]
209     res = ssid_obj.update_ssid(**sargs)
210     if not res:
211     nerrors += 1
212     si += 1
213    
214     if 'switches' in net[nname]:
215     for switch in net[nname]['switches']:
216     serial = switch.keys()[0]
217     dev_obj = meraki_api.Device(
218     key=config['api_key'], id=serial, net=net_obj)
219     if not dev_obj.realize():
220     print('Device {} is not in network {}'.format(
221     serial, net_obj.get('name')))
222     nerrors += 1
223     continue
224    
225     for switchport in switch[serial]:
226     port_range = switchport.keys()[0]
227     ports = []
228     if isinstance(port_range, (int, long)):
229     port_obj = meraki_api.SwitchPort(
230     key=config['api_key'], id=port_range, dev=dev_obj)
231     ports.append(port_obj)
232     else:
233     prs = port_range.split(',')
234     for pr in prs:
235     pr = pr.strip()
236     if isinstance(pr, (int, long)):
237     port_obj = meraki_api.SwitchPort(
238     key=config['api_key'], id=pr, dev=dev_obj)
239     ports.append(pr)
240     else:
241     if '-' not in pr:
242     print('Port range {} is invalid.'.format(pr))
243     nerrors += 1
244     continue
245    
246     (start, end) = pr.split('-')
247     start = start.strip()
248     end = end.strip()
249     if not isinstance(start, (int, long)) or not isinstance(end, (int, long)):
250     print('Error with port range {} and {} must be integers'.format(
251     pr, start, end))
252     nerrors += 1
253     continue
254    
255     if start >= end:
256     print(
257     'Error with port range {}; start must be less than end'.format(pr))
258     nerrors += 1
259     continue
260    
261     pi = start
262     while pi <= end:
263     port_obj = meraki_api.SwitchPort(
264     key=config['api_key'], id=pi, dev=dev_obj)
265     ports.append(port_obj)
266     pi += 1
267    
268     for port in ports:
269     pargs = {}
270     for key in ['name', 'tags', 'enabled', 'type', 'vlan', 'voice_vlan', 'allowed_vlans', 'poe_enabled']:
271     if key in switchport[port_range]:
272     pargs[key] = switchport[port_range][key]
273     res = port.update_switchport(**pargs)
274     if not res:
275     nerrors += 1
276    
277     if nerrors == 0:
278     print('Network {} has been setup successfully!'.format(nname))
279     else:
280     print(
281     'Error fully configuring network {}. See the errors above for more details.'.format(nname))
282     errors += nerrors
283    
284     if errors == 0:
285     print('All networks have been setup successfully!')
286     else:
287     print('There were errors setting up some of the networks. See the output above for more details.')
288     sys.exit(1)
289    
290    
291     if __name__ == '__main__':
292     main()

Properties

Name Value
svn:executable *

  ViewVC Help
Powered by ViewVC 1.1.27