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

Annotation of /meraki/setup_meraki_nets.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 20553 - (hide annotations) (download) (as text)
Tue May 8 03:22:40 2018 UTC (23 months ago) by jclarke
File MIME type: text/x-python
File size: 12502 byte(s)
Cleanup code.

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

Properties

Name Value
svn:executable *

  ViewVC Help
Powered by ViewVC 1.1.27