Debian Codegraph @

ansible_collections/community/general/plugins/modules/snmp_facts.py

raw
1 #!/usr/bin/python
2
3 # This file is part of Networklore's snmp library for Ansible
4 # Copyright (c) Ansible project
5 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
6 # SPDX-License-Identifier: GPL-3.0-or-later
7
8 from __future__ import annotations
9
10 DOCUMENTATION = r"""
11 module: snmp_facts
12 author:
13 - Patrick Ogenstad (@ogenstad)
14 - Laurenz Altenmueller (@lalten)
15 short_description: Retrieve facts for a device using SNMP
16 description:
17 - Retrieve facts for a device using SNMP. The facts are inserted to the RV(ansible_facts) key.
18 requirements:
19 - pysnmp (either pysnmp < 6.2.4 or pysnmp >= 7.1)
20 extends_documentation_fragment:
21 - community.general._attributes
22 - community.general._attributes.facts
23 - community.general._attributes.facts_module
24 attributes:
25 check_mode:
26 version_added: 3.3.0
27 # This was backported to 2.5.4 and 1.3.11 as well, since this was a bugfix
28 options:
29 host:
30 description:
31 - Set to target SNMP server (normally C({{ inventory_hostname }})).
32 type: str
33 required: true
34 version:
35 description:
36 - SNMP Version to use, V(v2), V(v2c) or V(v3).
37 type: str
38 required: true
39 choices: [v2, v2c, v3]
40 community:
41 description:
42 - The SNMP community string, required if O(version) is V(v2) or V(v2c).
43 type: str
44 level:
45 description:
46 - Authentication level.
47 - Required if O(version=v3).
48 type: str
49 choices: [authNoPriv, authPriv]
50 username:
51 description:
52 - Username for SNMPv3.
53 - Required if O(version=v3).
54 type: str
55 integrity:
56 description:
57 - Hashing algorithm.
58 - Required if O(version=v3).
59 type: str
60 choices: [md5, sha]
61 authkey:
62 description:
63 - Authentication key.
64 - Required O(version=v3).
65 type: str
66 privacy:
67 description:
68 - Encryption algorithm.
69 - Required if O(level=authPriv).
70 type: str
71 choices: [aes, des]
72 privkey:
73 description:
74 - Encryption key.
75 - Required if O(level=authPriv).
76 type: str
77 timeout:
78 description:
79 - Response timeout in seconds.
80 type: int
81 version_added: 2.3.0
82 retries:
83 description:
84 - Maximum number of request retries, 0 retries means just a single request.
85 type: int
86 version_added: 2.3.0
87 notes:
88 - Upgrading to pysnmp 7.1+ is recommended. Support for pysnmp 6.2 will be deprecated.
89 """
90
91 EXAMPLES = r"""
92 - name: Gather facts with SNMP version 2
93 community.general.snmp_facts:
94 host: '{{ inventory_hostname }}'
95 version: v2c
96 community: public
97 delegate_to: local
98
99 - name: Gather facts using SNMP version 3
100 community.general.snmp_facts:
101 host: '{{ inventory_hostname }}'
102 version: v3
103 level: authPriv
104 integrity: sha
105 privacy: aes
106 username: snmp-user
107 authkey: abc12345
108 privkey: def6789
109 delegate_to: localhost
110 """
111
112 RETURN = r"""
113 ansible_facts:
114 description: The returned facts.
115 returned: success
116 type: dict
117 contains:
118 ansible_sysdescr:
119 description: A textual description of the entity.
120 returned: success
121 type: str
122 sample: "Linux ubuntu-user 4.4.0-93-generic #116-Ubuntu SMP Fri Aug 11 21:17:51 UTC 2017 x86_64"
123 ansible_sysobjectid:
124 description: The vendor's authoritative identification of the network management subsystem contained in the entity.
125 returned: success
126 type: str
127 sample: 1.3.6.1.4.1.8072.3.2.10
128 ansible_sysuptime:
129 description: The time (in hundredths of a second) since the network management portion of the system was last re-initialized.
130 returned: success
131 type: int
132 sample: 42388
133 ansible_syscontact:
134 description: The textual identification of the contact person for this managed node, together with information on how to
135 contact this person.
136 returned: success
137 type: str
138 sample: Me <[email protected]>
139 ansible_sysname:
140 description: An administratively-assigned name for this managed node.
141 returned: success
142 type: str
143 sample: ubuntu-user
144 ansible_syslocation:
145 description: The physical location of this node (for example, V(telephone closet, 3rd floor)).
146 returned: success
147 type: str
148 sample: Sitting on the Dock of the Bay
149 ansible_all_ipv4_addresses:
150 description: List of all IPv4 addresses.
151 returned: success
152 type: list
153 sample: ["127.0.0.1", "172.17.0.1"]
154 ansible_interfaces:
155 description: Dictionary of each network interface and its metadata.
156 returned: success
157 type: dict
158 sample:
159 {
160 "1": {
161 "adminstatus": "up",
162 "description": "",
163 "ifindex": "1",
164 "ipv4": [
165 {
166 "address": "127.0.0.1",
167 "netmask": "255.0.0.0"
168 }
169 ],
170 "mac": "",
171 "mtu": "65536",
172 "name": "lo",
173 "operstatus": "up",
174 "speed": "65536"
175 },
176 "2": {
177 "adminstatus": "up",
178 "description": "",
179 "ifindex": "2",
180 "ipv4": [
181 {
182 "address": "192.168.213.128",
183 "netmask": "255.255.255.0"
184 }
185 ],
186 "mac": "000a305a52a1",
187 "mtu": "1500",
188 "name": "Intel Corporation 82545EM Gigabit Ethernet Controller (Copper)",
189 "operstatus": "up",
190 "speed": "1500"
191 }
192 }
193 """
194
195 import asyncio
196 import binascii
197 from collections import defaultdict
198
199 from ansible.module_utils.basic import AnsibleModule
200 from ansible.module_utils.common.text.converters import to_text
201
202 from ansible_collections.community.general.plugins.module_utils import _deps as deps
203
204 with deps.declare("pysnmp", url="https://pypi.org/project/pysnmp/"):
205 from pysnmp.hlapi.v3arch.asyncio import (
206 USM_AUTH_HMAC96_MD5,
207 USM_AUTH_HMAC96_SHA,
208 USM_PRIV_CBC56_DES,
209 USM_PRIV_CFB128_AES,
210 CommunityData,
211 ContextData,
212 ObjectIdentity,
213 ObjectType,
214 SnmpEngine,
215 UdpTransportTarget,
216 UsmUserData,
217 get_cmd,
218 next_cmd,
219 )
220 from pysnmp.proto.rfc1905 import EndOfMibView
221
222 with deps.declare("pysnmp6", url="https://pypi.org/project/pysnmp/"):
223 from pysnmp.entity.rfc3413.oneliner import cmdgen
224 from pysnmp.proto.rfc1905 import EndOfMibView
225
226 SNMP_DEFAULT_PORT = 161
227
228
229 class DefineOid:
230 def __init__(self, dotprefix=False):
231 if dotprefix:
232 dp = "."
233 else:
234 dp = ""
235
236 # From SNMPv2-MIB
237 self.sysDescr = f"{dp}1.3.6.1.2.1.1.1.0"
238 self.sysObjectId = f"{dp}1.3.6.1.2.1.1.2.0"
239 self.sysUpTime = f"{dp}1.3.6.1.2.1.1.3.0"
240 self.sysContact = f"{dp}1.3.6.1.2.1.1.4.0"
241 self.sysName = f"{dp}1.3.6.1.2.1.1.5.0"
242 self.sysLocation = f"{dp}1.3.6.1.2.1.1.6.0"
243
244 # From IF-MIB
245 self.ifIndex = f"{dp}1.3.6.1.2.1.2.2.1.1"
246 self.ifDescr = f"{dp}1.3.6.1.2.1.2.2.1.2"
247 self.ifMtu = f"{dp}1.3.6.1.2.1.2.2.1.4"
248 self.ifSpeed = f"{dp}1.3.6.1.2.1.2.2.1.5"
249 self.ifPhysAddress = f"{dp}1.3.6.1.2.1.2.2.1.6"
250 self.ifAdminStatus = f"{dp}1.3.6.1.2.1.2.2.1.7"
251 self.ifOperStatus = f"{dp}1.3.6.1.2.1.2.2.1.8"
252 self.ifAlias = f"{dp}1.3.6.1.2.1.31.1.1.1.18"
253
254 # From IP-MIB
255 self.ipAdEntAddr = f"{dp}1.3.6.1.2.1.4.20.1.1"
256 self.ipAdEntIfIndex = f"{dp}1.3.6.1.2.1.4.20.1.2"
257 self.ipAdEntNetMask = f"{dp}1.3.6.1.2.1.4.20.1.3"
258
259
260 def decode_hex(hexstring):
261 if len(hexstring) < 3:
262 return hexstring
263 if hexstring[:2] == "0x":
264 return to_text(binascii.unhexlify(hexstring[2:]))
265 return hexstring
266
267
268 def decode_mac(hexstring):
269 if len(hexstring) != 14:
270 return hexstring
271 if hexstring[:2] == "0x":
272 return hexstring[2:]
273 return hexstring
274
275
276 def lookup_adminstatus(int_adminstatus):
277 adminstatus_options = {1: "up", 2: "down", 3: "testing"}
278 return adminstatus_options.get(int_adminstatus, "")
279
280
281 def lookup_operstatus(int_operstatus):
282 operstatus_options = {
283 1: "up",
284 2: "down",
285 3: "testing",
286 4: "unknown",
287 5: "dormant",
288 6: "notPresent",
289 7: "lowerLayerDown",
290 }
291 return operstatus_options.get(int_operstatus, "")
292
293
294 def main():
295 module = AnsibleModule(
296 argument_spec=dict(
297 host=dict(type="str", required=True),
298 version=dict(type="str", required=True, choices=["v2", "v2c", "v3"]),
299 community=dict(type="str"),
300 username=dict(type="str"),
301 level=dict(type="str", choices=["authNoPriv", "authPriv"]),
302 integrity=dict(type="str", choices=["md5", "sha"]),
303 privacy=dict(type="str", choices=["aes", "des"]),
304 authkey=dict(type="str", no_log=True),
305 privkey=dict(type="str", no_log=True),
306 timeout=dict(type="int"),
307 retries=dict(type="int"),
308 ),
309 required_together=(
310 ["username", "level", "integrity", "authkey"],
311 ["privacy", "privkey"],
312 ),
313 required_if=[
314 ("version", "v2", ["community"]),
315 ("version", "v2c", ["community"]),
316 ("version", "v3", ["username", "authkey", "level"]),
317 ],
318 supports_check_mode=True,
319 )
320
321 m_args = module.params
322
323 if not deps.failed("pysnmp"):
324 return asyncio.run(_async_main(module, m_args))
325
326 deps.validate(module, "pysnmp6")
327
328 cmdGen = cmdgen.CommandGenerator()
329 transport_opts = {k: m_args[k] for k in ("timeout", "retries") if m_args[k] is not None}
330
331 integrity_proto = None
332 privacy_proto = None
333 if m_args["version"] == "v3":
334 if m_args["level"] == "authPriv" and m_args["privacy"] is None:
335 module.fail_json(msg="Privacy algorithm not set when using authPriv")
336
337 if m_args["integrity"] == "sha":
338 integrity_proto = cmdgen.usmHMACSHAAuthProtocol
339 elif m_args["integrity"] == "md5":
340 integrity_proto = cmdgen.usmHMACMD5AuthProtocol
341
342 if m_args["privacy"] == "aes":
343 privacy_proto = cmdgen.usmAesCfb128Protocol
344 elif m_args["privacy"] == "des":
345 privacy_proto = cmdgen.usmDESPrivProtocol
346
347 # Use SNMP Version 2
348 if m_args["version"] in ("v2", "v2c"):
349 snmp_auth = cmdgen.CommunityData(m_args["community"])
350
351 # Use SNMP Version 3 with authNoPriv
352 elif m_args["level"] == "authNoPriv":
353 snmp_auth = cmdgen.UsmUserData(m_args["username"], authKey=m_args["authkey"], authProtocol=integrity_proto)
354
355 # Use SNMP Version 3 with authPriv
356 else:
357 snmp_auth = cmdgen.UsmUserData(
358 m_args["username"],
359 authKey=m_args["authkey"],
360 privKey=m_args["privkey"],
361 authProtocol=integrity_proto,
362 privProtocol=privacy_proto,
363 )
364
365 # Use p to prefix OIDs with a dot for polling
366 p = DefineOid(dotprefix=True)
367 # Use v without a prefix to use with return values
368 v = DefineOid(dotprefix=False)
369
370 def Tree():
371 return defaultdict(Tree)
372
373 results = Tree()
374
375 errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd(
376 snmp_auth,
377 cmdgen.UdpTransportTarget((m_args["host"], 161), **transport_opts),
378 cmdgen.MibVariable(
379 p.sysDescr,
380 ),
381 cmdgen.MibVariable(
382 p.sysObjectId,
383 ),
384 cmdgen.MibVariable(
385 p.sysUpTime,
386 ),
387 cmdgen.MibVariable(
388 p.sysContact,
389 ),
390 cmdgen.MibVariable(
391 p.sysName,
392 ),
393 cmdgen.MibVariable(
394 p.sysLocation,
395 ),
396 lookupMib=False,
397 )
398
399 if errorIndication:
400 module.fail_json(msg=str(errorIndication))
401
402 for oid, val in varBinds:
403 current_oid = oid.prettyPrint()
404 current_val = val.prettyPrint()
405 if current_oid == v.sysDescr:
406 results["ansible_sysdescr"] = decode_hex(current_val)
407 elif current_oid == v.sysObjectId:
408 results["ansible_sysobjectid"] = current_val
409 elif current_oid == v.sysUpTime:
410 results["ansible_sysuptime"] = current_val
411 elif current_oid == v.sysContact:
412 results["ansible_syscontact"] = current_val
413 elif current_oid == v.sysName:
414 results["ansible_sysname"] = current_val
415 elif current_oid == v.sysLocation:
416 results["ansible_syslocation"] = current_val
417
418 errorIndication, errorStatus, errorIndex, varTable = cmdGen.nextCmd(
419 snmp_auth,
420 cmdgen.UdpTransportTarget((m_args["host"], 161), **transport_opts),
421 cmdgen.MibVariable(
422 p.ifIndex,
423 ),
424 cmdgen.MibVariable(
425 p.ifDescr,
426 ),
427 cmdgen.MibVariable(
428 p.ifMtu,
429 ),
430 cmdgen.MibVariable(
431 p.ifSpeed,
432 ),
433 cmdgen.MibVariable(
434 p.ifPhysAddress,
435 ),
436 cmdgen.MibVariable(
437 p.ifAdminStatus,
438 ),
439 cmdgen.MibVariable(
440 p.ifOperStatus,
441 ),
442 cmdgen.MibVariable(
443 p.ipAdEntAddr,
444 ),
445 cmdgen.MibVariable(
446 p.ipAdEntIfIndex,
447 ),
448 cmdgen.MibVariable(
449 p.ipAdEntNetMask,
450 ),
451 cmdgen.MibVariable(
452 p.ifAlias,
453 ),
454 lookupMib=False,
455 )
456
457 if errorIndication:
458 module.fail_json(msg=str(errorIndication))
459
460 interface_indexes = []
461
462 all_ipv4_addresses = []
463 ipv4_networks = Tree()
464
465 for varBinds in varTable:
466 for oid, val in varBinds:
467 if isinstance(val, EndOfMibView):
468 continue
469 current_oid = oid.prettyPrint()
470 current_val = val.prettyPrint()
471 if v.ifIndex in current_oid:
472 ifIndex = int(current_oid.rsplit(".", 1)[-1])
473 results["ansible_interfaces"][ifIndex]["ifindex"] = current_val
474 interface_indexes.append(ifIndex)
475 if v.ifDescr in current_oid:
476 ifIndex = int(current_oid.rsplit(".", 1)[-1])
477 results["ansible_interfaces"][ifIndex]["name"] = current_val
478 if v.ifMtu in current_oid:
479 ifIndex = int(current_oid.rsplit(".", 1)[-1])
480 results["ansible_interfaces"][ifIndex]["mtu"] = current_val
481 if v.ifSpeed in current_oid:
482 ifIndex = int(current_oid.rsplit(".", 1)[-1])
483 results["ansible_interfaces"][ifIndex]["speed"] = current_val
484 if v.ifPhysAddress in current_oid:
485 ifIndex = int(current_oid.rsplit(".", 1)[-1])
486 results["ansible_interfaces"][ifIndex]["mac"] = decode_mac(current_val)
487 if v.ifAdminStatus in current_oid:
488 ifIndex = int(current_oid.rsplit(".", 1)[-1])
489 results["ansible_interfaces"][ifIndex]["adminstatus"] = lookup_adminstatus(int(current_val))
490 if v.ifOperStatus in current_oid:
491 ifIndex = int(current_oid.rsplit(".", 1)[-1])
492 results["ansible_interfaces"][ifIndex]["operstatus"] = lookup_operstatus(int(current_val))
493 if v.ipAdEntAddr in current_oid:
494 curIPList = current_oid.rsplit(".", 4)[-4:]
495 curIP = ".".join(curIPList)
496 ipv4_networks[curIP]["address"] = current_val
497 all_ipv4_addresses.append(current_val)
498 if v.ipAdEntIfIndex in current_oid:
499 curIPList = current_oid.rsplit(".", 4)[-4:]
500 curIP = ".".join(curIPList)
501 ipv4_networks[curIP]["interface"] = current_val
502 if v.ipAdEntNetMask in current_oid:
503 curIPList = current_oid.rsplit(".", 4)[-4:]
504 curIP = ".".join(curIPList)
505 ipv4_networks[curIP]["netmask"] = current_val
506
507 if v.ifAlias in current_oid:
508 ifIndex = int(current_oid.rsplit(".", 1)[-1])
509 results["ansible_interfaces"][ifIndex]["description"] = current_val
510
511 interface_to_ipv4 = {}
512 for ipv4_network in ipv4_networks:
513 current_interface = ipv4_networks[ipv4_network]["interface"]
514 current_network = {
515 "address": ipv4_networks[ipv4_network]["address"],
516 "netmask": ipv4_networks[ipv4_network]["netmask"],
517 }
518 if current_interface not in interface_to_ipv4:
519 interface_to_ipv4[current_interface] = []
520 interface_to_ipv4[current_interface].append(current_network)
521 else:
522 interface_to_ipv4[current_interface].append(current_network)
523
524 for interface in interface_to_ipv4:
525 results["ansible_interfaces"][int(interface)]["ipv4"] = interface_to_ipv4[interface]
526
527 results["ansible_all_ipv4_addresses"] = all_ipv4_addresses
528
529 module.exit_json(ansible_facts=results)
530
531
532 async def _async_main(module, m_args):
533 """SNMP facts retrieval using pysnmp >= 7.1 async v3arch API."""
534 transport_opts = {k: m_args[k] for k in ("timeout", "retries") if m_args[k] is not None}
535
536 integrity_proto = None
537 privacy_proto = None
538 if m_args["version"] == "v3":
539 if m_args["level"] == "authPriv" and m_args["privacy"] is None:
540 module.fail_json(msg="Privacy algorithm not set when using authPriv")
541
542 if m_args["integrity"] == "sha":
543 integrity_proto = USM_AUTH_HMAC96_SHA
544 elif m_args["integrity"] == "md5":
545 integrity_proto = USM_AUTH_HMAC96_MD5
546
547 if m_args["privacy"] == "aes":
548 privacy_proto = USM_PRIV_CFB128_AES
549 elif m_args["privacy"] == "des":
550 privacy_proto = USM_PRIV_CBC56_DES
551
552 # Use SNMP Version 2
553 if m_args["version"] in ("v2", "v2c"):
554 snmp_auth = CommunityData(m_args["community"])
555
556 # Use SNMP Version 3 with authNoPriv
557 elif m_args["level"] == "authNoPriv":
558 snmp_auth = UsmUserData(m_args["username"], authKey=m_args["authkey"], authProtocol=integrity_proto)
559
560 # Use SNMP Version 3 with authPriv
561 else:
562 snmp_auth = UsmUserData(
563 m_args["username"],
564 authKey=m_args["authkey"],
565 privKey=m_args["privkey"],
566 authProtocol=integrity_proto,
567 privProtocol=privacy_proto,
568 )
569
570 # Use p to prefix OIDs with a dot for polling
571 p = DefineOid(dotprefix=True)
572 # Use v without a prefix to use with return values
573 v = DefineOid(dotprefix=False)
574
575 def Tree():
576 return defaultdict(Tree)
577
578 results = Tree()
579
580 transport = await UdpTransportTarget.create((m_args["host"], SNMP_DEFAULT_PORT), **transport_opts)
581 snmpEngine = SnmpEngine()
582
583 errorIndication, errorStatus, errorIndex, varBinds = await get_cmd(
584 snmpEngine,
585 snmp_auth,
586 transport,
587 ContextData(),
588 ObjectType(ObjectIdentity(p.sysDescr)),
589 ObjectType(ObjectIdentity(p.sysObjectId)),
590 ObjectType(ObjectIdentity(p.sysUpTime)),
591 ObjectType(ObjectIdentity(p.sysContact)),
592 ObjectType(ObjectIdentity(p.sysName)),
593 ObjectType(ObjectIdentity(p.sysLocation)),
594 lookupMib=False,
595 )
596
597 if errorIndication:
598 module.fail_json(msg=str(errorIndication))
599
600 for oid, val in varBinds:
601 current_oid = oid.prettyPrint()
602 current_val = val.prettyPrint()
603 if current_oid == v.sysDescr:
604 results["ansible_sysdescr"] = decode_hex(current_val)
605 elif current_oid == v.sysObjectId:
606 results["ansible_sysobjectid"] = current_val
607 elif current_oid == v.sysUpTime:
608 results["ansible_sysuptime"] = current_val
609 elif current_oid == v.sysContact:
610 results["ansible_syscontact"] = current_val
611 elif current_oid == v.sysName:
612 results["ansible_sysname"] = current_val
613 elif current_oid == v.sysLocation:
614 results["ansible_syslocation"] = current_val
615
616 oids = [
617 ObjectType(ObjectIdentity(p.ifIndex)),
618 ObjectType(ObjectIdentity(p.ifDescr)),
619 ObjectType(ObjectIdentity(p.ifMtu)),
620 ObjectType(ObjectIdentity(p.ifSpeed)),
621 ObjectType(ObjectIdentity(p.ifPhysAddress)),
622 ObjectType(ObjectIdentity(p.ifAdminStatus)),
623 ObjectType(ObjectIdentity(p.ifOperStatus)),
624 ObjectType(ObjectIdentity(p.ipAdEntAddr)),
625 ObjectType(ObjectIdentity(p.ipAdEntIfIndex)),
626 ObjectType(ObjectIdentity(p.ipAdEntNetMask)),
627 ObjectType(ObjectIdentity(p.ifAlias)),
628 ]
629 base_oids = [
630 v.ifIndex,
631 v.ifDescr,
632 v.ifMtu,
633 v.ifSpeed,
634 v.ifPhysAddress,
635 v.ifAdminStatus,
636 v.ifOperStatus,
637 v.ipAdEntAddr,
638 v.ipAdEntIfIndex,
639 v.ipAdEntNetMask,
640 v.ifAlias,
641 ]
642
643 varTable = []
644 while True:
645 errorIndication, errorStatus, errorIndex, varBinds_walk = await next_cmd(
646 snmpEngine,
647 snmp_auth,
648 transport,
649 ContextData(),
650 *oids,
651 lookupMib=False,
652 )
653
654 if errorIndication:
655 module.fail_json(msg=str(errorIndication))
656
657 if errorStatus:
658 break
659
660 # Stop when all OIDs have left their base subtree or hit EndOfMibView
661 if all(
662 isinstance(vb[1], EndOfMibView) or not vb[0].prettyPrint().startswith(base + ".")
663 for vb, base in zip(varBinds_walk, base_oids)
664 ):
665 break
666
667 varTable.append(varBinds_walk)
668 oids = varBinds_walk
669
670 interface_indexes = []
671
672 all_ipv4_addresses = []
673 ipv4_networks = Tree()
674
675 for varBinds in varTable:
676 for oid, val in varBinds:
677 if isinstance(val, EndOfMibView):
678 continue
679 current_oid = oid.prettyPrint()
680 current_val = val.prettyPrint()
681 if v.ifIndex in current_oid:
682 ifIndex = int(current_oid.rsplit(".", 1)[-1])
683 results["ansible_interfaces"][ifIndex]["ifindex"] = current_val
684 interface_indexes.append(ifIndex)
685 if v.ifDescr in current_oid:
686 ifIndex = int(current_oid.rsplit(".", 1)[-1])
687 results["ansible_interfaces"][ifIndex]["name"] = current_val
688 if v.ifMtu in current_oid:
689 ifIndex = int(current_oid.rsplit(".", 1)[-1])
690 results["ansible_interfaces"][ifIndex]["mtu"] = current_val
691 if v.ifSpeed in current_oid:
692 ifIndex = int(current_oid.rsplit(".", 1)[-1])
693 results["ansible_interfaces"][ifIndex]["speed"] = current_val
694 if v.ifPhysAddress in current_oid:
695 ifIndex = int(current_oid.rsplit(".", 1)[-1])
696 results["ansible_interfaces"][ifIndex]["mac"] = decode_mac(current_val)
697 if v.ifAdminStatus in current_oid:
698 ifIndex = int(current_oid.rsplit(".", 1)[-1])
699 results["ansible_interfaces"][ifIndex]["adminstatus"] = lookup_adminstatus(int(current_val))
700 if v.ifOperStatus in current_oid:
701 ifIndex = int(current_oid.rsplit(".", 1)[-1])
702 results["ansible_interfaces"][ifIndex]["operstatus"] = lookup_operstatus(int(current_val))
703 if v.ipAdEntAddr in current_oid:
704 curIPList = current_oid.rsplit(".", 4)[-4:]
705 curIP = ".".join(curIPList)
706 ipv4_networks[curIP]["address"] = current_val
707 all_ipv4_addresses.append(current_val)
708 if v.ipAdEntIfIndex in current_oid:
709 curIPList = current_oid.rsplit(".", 4)[-4:]
710 curIP = ".".join(curIPList)
711 ipv4_networks[curIP]["interface"] = current_val
712 if v.ipAdEntNetMask in current_oid:
713 curIPList = current_oid.rsplit(".", 4)[-4:]
714 curIP = ".".join(curIPList)
715 ipv4_networks[curIP]["netmask"] = current_val
716
717 if v.ifAlias in current_oid:
718 ifIndex = int(current_oid.rsplit(".", 1)[-1])
719 results["ansible_interfaces"][ifIndex]["description"] = current_val
720
721 interface_to_ipv4 = {}
722 for ipv4_network in ipv4_networks:
723 current_interface = ipv4_networks[ipv4_network]["interface"]
724 current_network = {
725 "address": ipv4_networks[ipv4_network]["address"],
726 "netmask": ipv4_networks[ipv4_network]["netmask"],
727 }
728 if current_interface not in interface_to_ipv4:
729 interface_to_ipv4[current_interface] = []
730 interface_to_ipv4[current_interface].append(current_network)
731 else:
732 interface_to_ipv4[current_interface].append(current_network)
733
734 for interface in interface_to_ipv4:
735 results["ansible_interfaces"][int(interface)]["ipv4"] = interface_to_ipv4[interface]
736
737 results["ansible_all_ipv4_addresses"] = all_ipv4_addresses
738
739 module.exit_json(ansible_facts=results)
740
741
742 if __name__ == "__main__":
743 main()