├── .gitignore
├── .pre-commit-config.yaml
├── .pylintrc
├── .readthedocs.yaml
├── CHANGELOG.txt
├── CODE_OF_CONDUCT.md
├── LICENSE.txt
├── MANIFEST.in
├── NOTICE
├── README.md
├── antani.py
├── docs
├── Makefile
├── conf.py
├── extras
│ └── index.rst
├── index.rst
├── make.bat
├── netwalk.rst
├── requirements.txt
└── usage
│ └── index.rst
├── extras
├── discover_from_netbox
│ └── __main__.py
├── draw_network
│ ├── README.md
│ ├── draw_network.py
│ └── requirements.txt
├── import_meraki_ap
│ └── import_meraki_ap.py
└── import_to_netbox
│ ├── README.md
│ ├── __init__.py
│ └── requirements.txt
├── netwalk
├── __init__.py
├── device.py
├── fabric.py
├── interface.py
├── libs.py
└── textfsm_templates
│ ├── show_cdp_neigh_detail.textfsm
│ ├── show_interface.textfsm
│ ├── show_inventory.textfsm
│ └── show_lldp_neigh_detail.textfsm
├── requirements.txt
├── setup.py
└── tests
├── __init__.py
├── test_fabric.py
├── test_interface.py
└── test_switch.py
/.gitignore:
--------------------------------------------------------------------------------
1 | __pycache__/
2 | .venv/
3 | .vscode/
4 | *.pyc
5 | build/
6 | dist/
7 | docs/_build/
8 | docs/build/
9 | netwalk.egg-info/
10 | venv/
--------------------------------------------------------------------------------
/.pre-commit-config.yaml:
--------------------------------------------------------------------------------
1 | repos:
2 | # Standard hooks
3 | - repo: https://github.com/pre-commit/pre-commit-hooks
4 | rev: v3.4.0
5 | hooks:
6 | - id: check-added-large-files
7 | - id: check-case-conflict
8 | - id: check-merge-conflict
9 | - id: check-symlinks
10 | - id: check-yaml
11 | - id: debug-statements
12 | - id: end-of-file-fixer
13 | - id: mixed-line-ending
14 | - id: requirements-txt-fixer
15 | - id: trailing-whitespace
16 |
17 | - repo: https://github.com/pycqa/isort
18 | rev: 5.10.1
19 | hooks:
20 | - id: isort
21 | name: isort (python)
22 |
23 | # Changes tabs to spaces
24 | - repo: https://github.com/Lucas-C/pre-commit-hooks
25 | rev: v1.1.9
26 | hooks:
27 | - id: remove-tabs
28 |
29 | - repo: local
30 | hooks:
31 | - id: pytest-check
32 | name: pytest-check
33 | entry: pytest
34 | language: system
35 | pass_filenames: false
36 | always_run: true
37 |
38 | # - repo: local
39 | # hooks:
40 | # - id: pylint
41 | # name: pylint
42 | # entry: pylint
43 | # language: system
44 | # types: [python]
45 | # args:
46 | # [
47 | # "-rn", # Only display messages
48 | # "-sn", # Don't display the score
49 | # ]
50 |
--------------------------------------------------------------------------------
/.pylintrc:
--------------------------------------------------------------------------------
1 | [MAIN]
2 |
3 | # Analyse import fallback blocks. This can be used to support both Python 2 and
4 | # 3 compatible code, which means that the block might have code that exists
5 | # only in one or another interpreter, leading to false positives when analysed.
6 | analyse-fallback-blocks=no
7 |
8 | # Load and enable all available extensions. Use --list-extensions to see a list
9 | # all available extensions.
10 | #enable-all-extensions=
11 |
12 | # In error mode, messages with a category besides ERROR or FATAL are
13 | # suppressed, and no reports are done by default. Error mode is compatible with
14 | # disabling specific errors.
15 | #errors-only=
16 |
17 | # Always return a 0 (non-error) status code, even if lint errors are found.
18 | # This is primarily useful in continuous integration scripts.
19 | #exit-zero=
20 |
21 | # A comma-separated list of package or module names from where C extensions may
22 | # be loaded. Extensions are loading into the active Python interpreter and may
23 | # run arbitrary code.
24 | extension-pkg-allow-list=
25 |
26 | # A comma-separated list of package or module names from where C extensions may
27 | # be loaded. Extensions are loading into the active Python interpreter and may
28 | # run arbitrary code. (This is an alternative name to extension-pkg-allow-list
29 | # for backward compatibility.)
30 | extension-pkg-whitelist=
31 |
32 | # Return non-zero exit code if any of these messages/categories are detected,
33 | # even if score is above --fail-under value. Syntax same as enable. Messages
34 | # specified are enabled, while categories only check already-enabled messages.
35 | fail-on=
36 |
37 | # Specify a score threshold under which the program will exit with error.
38 | fail-under=10
39 |
40 | # Interpret the stdin as a python script, whose filename needs to be passed as
41 | # the module_or_package argument.
42 | #from-stdin=
43 |
44 | # Files or directories to be skipped. They should be base names, not paths.
45 | ignore=CVS
46 |
47 | # Add files or directories matching the regular expressions patterns to the
48 | # ignore-list. The regex matches against paths and can be in Posix or Windows
49 | # format. Because '\' represents the directory delimiter on Windows systems, it
50 | # can't be used as an escape character.
51 | ignore-paths=
52 |
53 | # Files or directories matching the regular expression patterns are skipped.
54 | # The regex matches against base names, not paths. The default value ignores
55 | # Emacs file locks
56 | ignore-patterns=^\.#
57 |
58 | # List of module names for which member attributes should not be checked
59 | # (useful for modules/projects where namespaces are manipulated during runtime
60 | # and thus existing member attributes cannot be deduced by static analysis). It
61 | # supports qualified module names, as well as Unix pattern matching.
62 | ignored-modules=
63 |
64 | # Python code to execute, usually for sys.path manipulation such as
65 | # pygtk.require().
66 | #init-hook=
67 |
68 | # Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the
69 | # number of processors available to use, and will cap the count on Windows to
70 | # avoid hangs.
71 | jobs=0
72 |
73 | # Control the amount of potential inferred values when inferring a single
74 | # object. This can help the performance when dealing with large functions or
75 | # complex, nested conditions.
76 | limit-inference-results=100
77 |
78 | # List of plugins (as comma separated values of python module names) to load,
79 | # usually to register additional checkers.
80 | load-plugins=
81 |
82 | # Pickle collected data for later comparisons.
83 | persistent=yes
84 |
85 | # Minimum Python version to use for version dependent checks. Will default to
86 | # the version used to run pylint.
87 | py-version=3.10
88 |
89 | # Discover python modules and packages in the file system subtree.
90 | recursive=no
91 |
92 | # When enabled, pylint would attempt to guess common misconfiguration and emit
93 | # user-friendly hints instead of false-positive error messages.
94 | suggestion-mode=yes
95 |
96 | # Allow loading of arbitrary C extensions. Extensions are imported into the
97 | # active Python interpreter and may run arbitrary code.
98 | unsafe-load-any-extension=no
99 |
100 | # In verbose mode, extra non-checker-related info will be displayed.
101 | #verbose=
102 |
103 |
104 | [BASIC]
105 |
106 | # Naming style matching correct argument names.
107 | argument-naming-style=snake_case
108 |
109 | # Regular expression matching correct argument names. Overrides argument-
110 | # naming-style. If left empty, argument names will be checked with the set
111 | # naming style.
112 | #argument-rgx=
113 |
114 | # Naming style matching correct attribute names.
115 | attr-naming-style=snake_case
116 |
117 | # Regular expression matching correct attribute names. Overrides attr-naming-
118 | # style. If left empty, attribute names will be checked with the set naming
119 | # style.
120 | #attr-rgx=
121 |
122 | # Bad variable names which should always be refused, separated by a comma.
123 | bad-names=foo,
124 | bar,
125 | baz,
126 | toto,
127 | tutu,
128 | tata
129 |
130 | # Bad variable names regexes, separated by a comma. If names match any regex,
131 | # they will always be refused
132 | bad-names-rgxs=
133 |
134 | # Naming style matching correct class attribute names.
135 | class-attribute-naming-style=any
136 |
137 | # Regular expression matching correct class attribute names. Overrides class-
138 | # attribute-naming-style. If left empty, class attribute names will be checked
139 | # with the set naming style.
140 | #class-attribute-rgx=
141 |
142 | # Naming style matching correct class constant names.
143 | class-const-naming-style=UPPER_CASE
144 |
145 | # Regular expression matching correct class constant names. Overrides class-
146 | # const-naming-style. If left empty, class constant names will be checked with
147 | # the set naming style.
148 | #class-const-rgx=
149 |
150 | # Naming style matching correct class names.
151 | class-naming-style=PascalCase
152 |
153 | # Regular expression matching correct class names. Overrides class-naming-
154 | # style. If left empty, class names will be checked with the set naming style.
155 | #class-rgx=
156 |
157 | # Naming style matching correct constant names.
158 | const-naming-style=UPPER_CASE
159 |
160 | # Regular expression matching correct constant names. Overrides const-naming-
161 | # style. If left empty, constant names will be checked with the set naming
162 | # style.
163 | #const-rgx=
164 |
165 | # Minimum line length for functions/classes that require docstrings, shorter
166 | # ones are exempt.
167 | docstring-min-length=-1
168 |
169 | # Naming style matching correct function names.
170 | function-naming-style=snake_case
171 |
172 | # Regular expression matching correct function names. Overrides function-
173 | # naming-style. If left empty, function names will be checked with the set
174 | # naming style.
175 | #function-rgx=
176 |
177 | # Good variable names which should always be accepted, separated by a comma.
178 | good-names=i,
179 | j,
180 | k,
181 | v,
182 | e,
183 | ex,
184 | Run,
185 | _
186 |
187 | # Good variable names regexes, separated by a comma. If names match any regex,
188 | # they will always be accepted
189 | good-names-rgxs=
190 |
191 | # Include a hint for the correct naming format with invalid-name.
192 | include-naming-hint=no
193 |
194 | # Naming style matching correct inline iteration names.
195 | inlinevar-naming-style=any
196 |
197 | # Regular expression matching correct inline iteration names. Overrides
198 | # inlinevar-naming-style. If left empty, inline iteration names will be checked
199 | # with the set naming style.
200 | #inlinevar-rgx=
201 |
202 | # Naming style matching correct method names.
203 | method-naming-style=snake_case
204 |
205 | # Regular expression matching correct method names. Overrides method-naming-
206 | # style. If left empty, method names will be checked with the set naming style.
207 | #method-rgx=
208 |
209 | # Naming style matching correct module names.
210 | module-naming-style=snake_case
211 |
212 | # Regular expression matching correct module names. Overrides module-naming-
213 | # style. If left empty, module names will be checked with the set naming style.
214 | #module-rgx=
215 |
216 | # Colon-delimited sets of names that determine each other's naming style when
217 | # the name regexes allow several styles.
218 | name-group=
219 |
220 | # Regular expression which should only match function or class names that do
221 | # not require a docstring.
222 | no-docstring-rgx=^_
223 |
224 | # List of decorators that produce properties, such as abc.abstractproperty. Add
225 | # to this list to register other decorators that produce valid properties.
226 | # These decorators are taken in consideration only for invalid-name.
227 | property-classes=abc.abstractproperty
228 |
229 | # Regular expression matching correct type variable names. If left empty, type
230 | # variable names will be checked with the set naming style.
231 | #typevar-rgx=
232 |
233 | # Naming style matching correct variable names.
234 | variable-naming-style=snake_case
235 |
236 | # Regular expression matching correct variable names. Overrides variable-
237 | # naming-style. If left empty, variable names will be checked with the set
238 | # naming style.
239 | #variable-rgx=
240 |
241 |
242 | [CLASSES]
243 |
244 | # Warn about protected attribute access inside special methods
245 | check-protected-access-in-special-methods=no
246 |
247 | # List of method names used to declare (i.e. assign) instance attributes.
248 | defining-attr-methods=__init__,
249 | __new__,
250 | setUp,
251 | __post_init__
252 |
253 | # List of member names, which should be excluded from the protected access
254 | # warning.
255 | exclude-protected=_asdict,
256 | _fields,
257 | _replace,
258 | _source,
259 | _make
260 |
261 | # List of valid names for the first argument in a class method.
262 | valid-classmethod-first-arg=cls
263 |
264 | # List of valid names for the first argument in a metaclass class method.
265 | valid-metaclass-classmethod-first-arg=cls
266 |
267 |
268 | [DESIGN]
269 |
270 | # List of regular expressions of class ancestor names to ignore when counting
271 | # public methods (see R0903)
272 | exclude-too-few-public-methods=
273 |
274 | # List of qualified class names to ignore when counting class parents (see
275 | # R0901)
276 | ignored-parents=
277 |
278 | # Maximum number of arguments for function / method.
279 | max-args=5
280 |
281 | # Maximum number of attributes for a class (see R0902).
282 | max-attributes=7
283 |
284 | # Maximum number of boolean expressions in an if statement (see R0916).
285 | max-bool-expr=5
286 |
287 | # Maximum number of branch for function / method body.
288 | max-branches=12
289 |
290 | # Maximum number of locals for function / method body.
291 | max-locals=15
292 |
293 | # Maximum number of parents for a class (see R0901).
294 | max-parents=7
295 |
296 | # Maximum number of public methods for a class (see R0904).
297 | max-public-methods=20
298 |
299 | # Maximum number of return / yield for function / method body.
300 | max-returns=6
301 |
302 | # Maximum number of statements in function / method body.
303 | max-statements=50
304 |
305 | # Minimum number of public methods for a class (see R0903).
306 | min-public-methods=2
307 |
308 |
309 | [EXCEPTIONS]
310 |
311 | # Exceptions that will emit a warning when caught.
312 | overgeneral-exceptions=BaseException,
313 | Exception
314 |
315 |
316 | [FORMAT]
317 |
318 | # Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
319 | expected-line-ending-format=
320 |
321 | # Regexp for a line that is allowed to be longer than the limit.
322 | ignore-long-lines=^\s*(# )??$
323 |
324 | # Number of spaces of indent required inside a hanging or continued line.
325 | indent-after-paren=4
326 |
327 | # String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
328 | # tab).
329 | indent-string=' '
330 |
331 | # Maximum number of characters on a single line.
332 | max-line-length=150
333 |
334 | # Maximum number of lines in a module.
335 | max-module-lines=1000
336 |
337 | # Allow the body of a class to be on the same line as the declaration if body
338 | # contains single statement.
339 | single-line-class-stmt=no
340 |
341 | # Allow the body of an if to be on the same line as the test if there is no
342 | # else.
343 | single-line-if-stmt=no
344 |
345 |
346 | [IMPORTS]
347 |
348 | # List of modules that can be imported at any level, not just the top level
349 | # one.
350 | allow-any-import-level=
351 |
352 | # Allow wildcard imports from modules that define __all__.
353 | allow-wildcard-with-all=no
354 |
355 | # Deprecated modules which should not be used, separated by a comma.
356 | deprecated-modules=
357 |
358 | # Output a graph (.gv or any supported image format) of external dependencies
359 | # to the given file (report RP0402 must not be disabled).
360 | ext-import-graph=
361 |
362 | # Output a graph (.gv or any supported image format) of all (i.e. internal and
363 | # external) dependencies to the given file (report RP0402 must not be
364 | # disabled).
365 | import-graph=
366 |
367 | # Output a graph (.gv or any supported image format) of internal dependencies
368 | # to the given file (report RP0402 must not be disabled).
369 | int-import-graph=
370 |
371 | # Force import order to recognize a module as part of the standard
372 | # compatibility libraries.
373 | known-standard-library=
374 |
375 | # Force import order to recognize a module as part of a third party library.
376 | known-third-party=enchant
377 |
378 | # Couples of modules and preferred modules, separated by a comma.
379 | preferred-modules=
380 |
381 |
382 | [LOGGING]
383 |
384 | # The type of string formatting that logging methods do. `old` means using %
385 | # formatting, `new` is for `{}` formatting.
386 | logging-format-style=old
387 |
388 | # Logging modules to check that the string format arguments are in logging
389 | # function parameter format.
390 | logging-modules=logging
391 |
392 |
393 | [MESSAGES CONTROL]
394 |
395 | # Only show warnings with the listed confidence levels. Leave empty to show
396 | # all. Valid levels: HIGH, CONTROL_FLOW, INFERENCE, INFERENCE_FAILURE,
397 | # UNDEFINED.
398 | confidence=HIGH,
399 | CONTROL_FLOW,
400 | INFERENCE,
401 | INFERENCE_FAILURE,
402 | UNDEFINED
403 |
404 | # Disable the message, report, category or checker with the given id(s). You
405 | # can either give multiple identifiers separated by comma (,) or put this
406 | # option multiple times (only on the command line, not in the configuration
407 | # file where it should appear only once). You can also use "--disable=all" to
408 | # disable everything first and then re-enable specific checks. For example, if
409 | # you want to run only the similarities checker, you can use "--disable=all
410 | # --enable=similarities". If you want to run only the classes checker, but have
411 | # no Warning level messages displayed, use "--disable=all --enable=classes
412 | # --disable=W".
413 | disable=unspecified-encoding
414 | ; disable=raw-checker-failed,
415 | ; bad-inline-option,
416 | ; locally-disabled,
417 | ; file-ignored,
418 | ; suppressed-message,
419 | ; useless-suppression,
420 | ; deprecated-pragma,
421 | ; use-symbolic-message-instead
422 |
423 | # Enable the message, report, category or checker with the given id(s). You can
424 | # either give multiple identifier separated by comma (,) or put this option
425 | # multiple time (only on the command line, not in the configuration file where
426 | # it should appear only once). See also the "--disable" option for examples.
427 | enable=c-extension-no-member
428 |
429 |
430 | [METHOD_ARGS]
431 |
432 | # List of qualified names (i.e., library.method) which require a timeout
433 | # parameter e.g. 'requests.api.get,requests.api.post'
434 | timeout-methods=requests.api.delete,requests.api.get,requests.api.head,requests.api.options,requests.api.patch,requests.api.post,requests.api.put,requests.api.request
435 |
436 |
437 | [MISCELLANEOUS]
438 |
439 | # List of note tags to take in consideration, separated by a comma.
440 | notes=FIXME,
441 | XXX,
442 | TODO
443 |
444 | # Regular expression of note tags to take in consideration.
445 | notes-rgx=
446 |
447 |
448 | [REFACTORING]
449 |
450 | # Maximum number of nested blocks for function / method body
451 | max-nested-blocks=5
452 |
453 | # Complete name of functions that never returns. When checking for
454 | # inconsistent-return-statements if a never returning function is called then
455 | # it will be considered as an explicit return statement and no message will be
456 | # printed.
457 | never-returning-functions=sys.exit,argparse.parse_error
458 |
459 |
460 | [REPORTS]
461 |
462 | # Python expression which should return a score less than or equal to 10. You
463 | # have access to the variables 'fatal', 'error', 'warning', 'refactor',
464 | # 'convention', and 'info' which contain the number of messages in each
465 | # category, as well as 'statement' which is the total number of statements
466 | # analyzed. This score is used by the global evaluation report (RP0004).
467 | evaluation=max(0, 0 if fatal else 10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10))
468 |
469 | # Template used to display messages. This is a python new-style format string
470 | # used to format the message information. See doc for all details.
471 | msg-template=
472 |
473 | # Set the output format. Available formats are text, parseable, colorized, json
474 | # and msvs (visual studio). You can also give a reporter class, e.g.
475 | # mypackage.mymodule.MyReporterClass.
476 | #output-format=
477 |
478 | # Tells whether to display a full report or only the messages.
479 | reports=no
480 |
481 | # Activate the evaluation score.
482 | score=yes
483 |
484 |
485 | [SIMILARITIES]
486 |
487 | # Comments are removed from the similarity computation
488 | ignore-comments=yes
489 |
490 | # Docstrings are removed from the similarity computation
491 | ignore-docstrings=yes
492 |
493 | # Imports are removed from the similarity computation
494 | ignore-imports=yes
495 |
496 | # Signatures are removed from the similarity computation
497 | ignore-signatures=yes
498 |
499 | # Minimum lines number of a similarity.
500 | min-similarity-lines=4
501 |
502 |
503 | [SPELLING]
504 |
505 | # Limits count of emitted suggestions for spelling mistakes.
506 | max-spelling-suggestions=4
507 |
508 | # Spelling dictionary name. Available dictionaries: none. To make it work,
509 | # install the 'python-enchant' package.
510 | spelling-dict=
511 |
512 | # List of comma separated words that should be considered directives if they
513 | # appear at the beginning of a comment and should not be checked.
514 | spelling-ignore-comment-directives=fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy:
515 |
516 | # List of comma separated words that should not be checked.
517 | spelling-ignore-words=
518 |
519 | # A path to a file that contains the private dictionary; one word per line.
520 | spelling-private-dict-file=
521 |
522 | # Tells whether to store unknown words to the private dictionary (see the
523 | # --spelling-private-dict-file option) instead of raising a message.
524 | spelling-store-unknown-words=no
525 |
526 |
527 | [STRING]
528 |
529 | # This flag controls whether inconsistent-quotes generates a warning when the
530 | # character used as a quote delimiter is used inconsistently within a module.
531 | check-quote-consistency=no
532 |
533 | # This flag controls whether the implicit-str-concat should generate a warning
534 | # on implicit string concatenation in sequences defined over several lines.
535 | check-str-concat-over-line-jumps=no
536 |
537 |
538 | [TYPECHECK]
539 |
540 | # List of decorators that produce context managers, such as
541 | # contextlib.contextmanager. Add to this list to register other decorators that
542 | # produce valid context managers.
543 | contextmanager-decorators=contextlib.contextmanager
544 |
545 | # List of members which are set dynamically and missed by pylint inference
546 | # system, and so shouldn't trigger E1101 when accessed. Python regular
547 | # expressions are accepted.
548 | generated-members=
549 |
550 | # Tells whether to warn about missing members when the owner of the attribute
551 | # is inferred to be None.
552 | ignore-none=yes
553 |
554 | # This flag controls whether pylint should warn about no-member and similar
555 | # checks whenever an opaque object is returned when inferring. The inference
556 | # can return multiple potential results while evaluating a Python object, but
557 | # some branches might not be evaluated, which results in partial inference. In
558 | # that case, it might be useful to still emit no-member and other checks for
559 | # the rest of the inferred objects.
560 | ignore-on-opaque-inference=yes
561 |
562 | # List of symbolic message names to ignore for Mixin members.
563 | ignored-checks-for-mixins=no-member,
564 | not-async-context-manager,
565 | not-context-manager,
566 | attribute-defined-outside-init
567 |
568 | # List of class names for which member attributes should not be checked (useful
569 | # for classes with dynamically set attributes). This supports the use of
570 | # qualified names.
571 | ignored-classes=optparse.Values,thread._local,_thread._local,argparse.Namespace
572 |
573 | # Show a hint with possible names when a member name was not found. The aspect
574 | # of finding the hint is based on edit distance.
575 | missing-member-hint=yes
576 |
577 | # The minimum edit distance a name should have in order to be considered a
578 | # similar match for a missing member name.
579 | missing-member-hint-distance=1
580 |
581 | # The total number of similar names that should be taken in consideration when
582 | # showing a hint for a missing member.
583 | missing-member-max-choices=1
584 |
585 | # Regex pattern to define which classes are considered mixins.
586 | mixin-class-rgx=.*[Mm]ixin
587 |
588 | # List of decorators that change the signature of a decorated function.
589 | signature-mutators=
590 |
591 |
592 | [VARIABLES]
593 |
594 | # List of additional names supposed to be defined in builtins. Remember that
595 | # you should avoid defining new builtins when possible.
596 | additional-builtins=
597 |
598 | # Tells whether unused global variables should be treated as a violation.
599 | allow-global-unused-variables=yes
600 |
601 | # List of names allowed to shadow builtins
602 | allowed-redefined-builtins=
603 |
604 | # List of strings which can identify a callback function by name. A callback
605 | # name must start or end with one of those strings.
606 | callbacks=cb_,
607 | _cb
608 |
609 | # A regular expression matching the name of dummy variables (i.e. expected to
610 | # not be used).
611 | dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_
612 |
613 | # Argument names that match this expression will be ignored.
614 | ignored-argument-names=_.*|^ignored_|^unused_
615 |
616 | # Tells whether we should check for unused import in __init__ files.
617 | init-import=no
618 |
619 | # List of qualified module names which can have objects that can redefine
620 | # builtins.
621 | redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io
622 |
--------------------------------------------------------------------------------
/.readthedocs.yaml:
--------------------------------------------------------------------------------
1 | version: 2
2 |
3 | python:
4 | version: 3.8
5 | install:
6 | - requirements: docs/requirements.txt
7 | - method: setuptools
8 | path: .
9 |
--------------------------------------------------------------------------------
/CHANGELOG.txt:
--------------------------------------------------------------------------------
1 | v1.6.1
2 | - Minor fixes
3 | - Dependency upgrades
4 |
5 | v1.6
6 | - BREAKING CHANGE: .switch attribute renamed to .device
7 | - Lots of stuff. Like seriously, lost track of it. My fault.
8 |
9 | v1.5
10 | - Better device lookup, should no longer have duplicate Device objects
11 | - Introduced callback function in Fabric.init_from_seed_device to allow external control whether to scan a discovered device or not (helps speeding up discovery by discarding those devices that are known to be inaccessible)
12 |
13 | v1.4
14 | Juicy stuff:
15 | - Switch is now a subclass of Device, a generic object for unmanaged devices
16 | - Neighbors are now always defined as Interface objects when creating a device inside of a Fabric
17 | - LLDP neighbor parsing
18 | - Calculate an integer to sort interfaces sensibly
19 | - Support for routed tagged interfaces ("encapsulation dot1q")
20 | - New Extra: import stuff from Meraki dashboard to Netbox
21 | - New Extra: run netwalk across a network importing data from Netbox
22 |
23 | Minor stuff:
24 | - Sessions to devices are now correctly closed
25 | - Add attribute mgmt_address, do not connect to devices via hostname alone
26 |
27 | v1.3.1 (bufgix)
28 | - Do not delete line from unparsed_lines if no PO interface is found
29 |
30 | v1.3
31 | - Add parsing of port channels
32 |
33 | v1.2
34 | - Add parsing of show inventory command
35 |
36 | v1.1.4
37 | - Get users from switch config
38 | - Allow to disable some information gathering from a switch (BREAKING CHANGE from v1.1.3 only)
39 |
40 | v1.1.3
41 | - Calculate a sort_order value for interfaces to sort by interface id, not
42 | merely alphabetical
43 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | Behave like your grandma was watching you
2 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published by
637 | the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
--------------------------------------------------------------------------------
/MANIFEST.in:
--------------------------------------------------------------------------------
1 | recursive-include netwalk/textfsm_templates *.textfsm
--------------------------------------------------------------------------------
/NOTICE:
--------------------------------------------------------------------------------
1 | netwalk
2 | Copyright (c) 2021 NTT Ltd
3 |
4 | This project includes software developed at NTT Ltd. and/or its affiliates.
5 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Netwalk
2 |
3 | Netwalk is a Python library born out of a large remadiation project aimed at making network device discovery and management as fast and painless as possible.
4 |
5 | ## Installation
6 | Can be installed via pip with `pip install netwalk`
7 |
8 | ### Extras
9 | A collection of scripts with extra features and examples is stored in the `extras` folder
10 |
11 | ### Code quality
12 | A lot of the code is covered by tests. More will be added in the future
13 |
14 | ## Fabric
15 |
16 | This object type defines an entire switched network and can be manually populated, have switches added one by one or you can give it one or more seed devices and it will go and scan everything for you.
17 |
18 | #### Auto scanning example:
19 | ```python
20 | from netwalk import Fabric
21 | sitename = Fabric()
22 | sitename.init_from_seed_device(seed_hosts=["10.10.10.1"],
23 | credentials=[("cisco","cisco"),("customer","password")]
24 | napalm_optional_args=[{'secret': 'cisco'}, {'transport': 'telnet'}])
25 | ```
26 |
27 | This code will start searching from device 10.10.10.1 and will try to log in via SSH with cisco/cisco and then customer/password.
28 | Once connected to the switch it will pull and parse the running config, the mac address table and the cdp neighbours, then will start cycling through all neighbours recursively until the entire fabric has been discovered
29 |
30 | Note: you may also pass a list of `napalm_optional_args`, check the [NAPALM optional args guide](https://napalm.readthedocs.io/en/latest/support/#optional-arguments) for explanation and examples
31 |
32 | ### Manual addition of switches
33 | You can tell Fabric to discover another switch on its own or you can add a `Switch` object to `.devices`. WHichever way, do not forget to call `refresh_global_information` to recalculate neighborships and global mac address table
34 |
35 | #### Example
36 |
37 | ```python
38 | sitename.add_switch(host="10.10.10.1",
39 | credentials=[("cisco","cisco"))
40 | sitename.refresh_global_information()
41 | ```
42 | Note: you may also pass a list of `napalm_optional_args`, check the [optional args guide](https://napalm.readthedocs.io/en/latest/support/#optional-arguments) for explanation and examples
43 | ### Structure
44 |
45 | `sitename` will now contain two main attributes:
46 | * `switches`, a dictionary of `{'hostname': Switch}`
47 | * `mac_table`, another dictionary containing a list of all macs in the fabric, the interface closest to them
48 |
49 |
50 | --------------
51 |
52 | ## Switch
53 | This object defines a switch. It can be created in two ways:
54 |
55 | #### Automatic connection
56 | ``` python
57 | from netwalk import Switch
58 | sw01 = Switch(hostname="10.10.10.1")
59 | sw01.retrieve_data(username="cisco",
60 | password="cisco"})
61 | ```
62 | Note: you may also pass a list of `napalm_optional_args`, check the [optional args guide](https://napalm.readthedocs.io/en/latest/support/#optional-arguments) for explanation and examples
63 |
64 | This will connect to the switch and pull all the data much like `add_switch()` does in `Fabric`
65 |
66 | ### Init from show run
67 | You may also generate the Switch device from a show run you have extracted somewhere else. This will not give you mac address table or neighborship discovery but will generate all Interfaces in the switch
68 |
69 | ``` python
70 | from netwalk import Switch
71 |
72 | showrun = """
73 | int gi 0/1
74 | switchport mode access
75 | ...
76 | int gi 0/24
77 | switchport mode trunk
78 | """
79 |
80 | sw01 = Switch(hostname="10.10.10.1", config=showrun)
81 | ```
82 |
83 | ### Structure
84 | A `Switch` object has the following attributes:
85 | * `hostname`: the IP or hostname to connect to
86 | * `config`: string containing plain text show run
87 | * `interfaces`: dictionary of `{'interface name', Interface}`}
88 | * `mac_table`: a dictionary containing the switch's mac address table
89 |
90 |
91 | ## Interface
92 | An Interface object defines a switched interface ("switchport" in Cisco language) and can hold data about its configuration such as:
93 |
94 | * `name`
95 | * `description`
96 | * `mode`: either "access" or "trunk"
97 | * `allowed_vlan`: a `set()` of vlans to tag
98 | * `native_vlan`
99 | * `voice_vlan`
100 | * `switch`: pointer to parent Switch
101 | * `is_up`: if the interface is active
102 | * `is_enabled`: shutdown ot not
103 | * `config`: its configuration
104 | * `mac_count`: number of MACs behind it
105 | * `type_edge`: also known as "portfast"
106 | * `bpduguard`
107 |
108 | Printing an interface yelds its configuration based on its current attributes
109 |
110 | ## Trick
111 |
112 | ### Check a trunk filter is equal on both sides
113 | ```python
114 | assert int.allowed_vlan == int.neighbors[0].allowed_vlan
115 | ```
116 |
117 | ### Check a particular host is in vlan 10
118 | ```python
119 | from netaddr import EUI
120 | host_mac = EUI('00:01:02:03:04:05')
121 | assert fabric.mac_table[host_mac]['interface'].native_vlan == 10
122 | ```
123 |
--------------------------------------------------------------------------------
/antani.py:
--------------------------------------------------------------------------------
1 | import netwalk
2 |
3 | fabric = netwalk.Fabric()
4 |
5 | fabric.init_from_seed_device("")
6 | c93 = netwalk.Switch("10.210.65.3.33")
7 |
8 | c93.retrieve_data("cisco", "cisco")
9 |
--------------------------------------------------------------------------------
/docs/Makefile:
--------------------------------------------------------------------------------
1 | # Minimal makefile for Sphinx documentation
2 | #
3 |
4 | # You can set these variables from the command line, and also
5 | # from the environment for the first two.
6 | SPHINXOPTS ?=
7 | SPHINXBUILD ?= sphinx-build
8 | SOURCEDIR = .
9 | BUILDDIR = _build
10 |
11 | # Put it first so that "make" without argument is like "make help".
12 | help:
13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
14 |
15 | .PHONY: help Makefile
16 |
17 | # Catch-all target: route all unknown targets to Sphinx using the new
18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
19 | %: Makefile
20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
21 |
--------------------------------------------------------------------------------
/docs/conf.py:
--------------------------------------------------------------------------------
1 | # Configuration file for the Sphinx documentation builder.
2 | #
3 | # This file only contains a selection of the most common options. For a full
4 | # list see the documentation:
5 | # https://www.sphinx-doc.org/en/master/usage/configuration.html
6 |
7 | # -- Path setup --------------------------------------------------------------
8 |
9 | # If extensions (or modules to document with autodoc) are in another directory,
10 | # add these directories to sys.path here. If the directory is relative to the
11 | # documentation root, use os.path.abspath to make it absolute, like shown here.
12 | #
13 | # import os
14 | # import sys
15 | # sys.path.insert(0, os.path.abspath('.'))
16 |
17 |
18 | # -- Project information -----------------------------------------------------
19 |
20 | project = 'Netwalk'
21 | copyright = '2021, icovada'
22 | author = 'icovada'
23 |
24 | # The full version, including alpha/beta/rc tags
25 | release = '1.4'
26 |
27 |
28 | # -- General configuration ---------------------------------------------------
29 |
30 | # Add any Sphinx extension module names here, as strings. They can be
31 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
32 | # ones.
33 | extensions = [
34 | 'sphinx.ext.autodoc'
35 | ]
36 |
37 | # Add any paths that contain templates here, relative to this directory.
38 | templates_path = ['_templates']
39 |
40 | # List of patterns, relative to source directory, that match files and
41 | # directories to ignore when looking for source files.
42 | # This pattern also affects html_static_path and html_extra_path.
43 | exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
44 |
45 |
46 | # -- Options for HTML output -------------------------------------------------
47 |
48 | # The theme to use for HTML and HTML Help pages. See the documentation for
49 | # a list of builtin themes.
50 | #
51 | html_theme = 'sphinx_rtd_theme'
52 |
53 | # Add any paths that contain custom static files (such as style sheets) here,
54 | # relative to this directory. They are copied after the builtin static files,
55 | # so a file named "default.css" will overwrite the builtin "default.css".
56 | html_static_path = ['_static']
--------------------------------------------------------------------------------
/docs/extras/index.rst:
--------------------------------------------------------------------------------
1 | Extras
2 | ======
3 |
4 | A handy collection of scripts is included under `extras`
--------------------------------------------------------------------------------
/docs/index.rst:
--------------------------------------------------------------------------------
1 | .. Netwalk documentation master file, created by
2 | sphinx-quickstart on Tue Oct 26 11:24:15 2021.
3 | You can adapt this file completely to your liking, but it should at least
4 | contain the root `toctree` directive.
5 |
6 | Netwalk
7 | =======
8 |
9 | Netwalk is a Python library born out of a large remadiation project aimed at making network device discovery and management as fast and as painless as possible.
10 |
11 | Usage is quite straightforward:
12 |
13 | .. code-block:: python
14 |
15 | from netwalk import Fabric
16 | sitename = Fabric()
17 | sitename.init_from_seed_device(seed_hosts=["10.10.10.1"],
18 | credentials=[("cisco","cisco"),("customer","password")]
19 | napalm_optional_args=[{}, {'transport': 'telnet'}])
20 |
21 |
22 | This code will start searching from device 10.10.10.1 and will try to log in via SSH with cisco/cisco and then customer/password, first via SSH then Telnet.
23 | Once connected to the switch it will pull and parse the running config, the mac address table and the cdp neighbours, then will start cycling through all neighbours recursively until the entire fabric has been discovered
24 |
25 |
26 |
27 | Installation
28 | ------------
29 | You can install napalm with pip:
30 |
31 | .. code-block:: bash
32 |
33 | pip install netwalk
34 |
35 | Extras
36 | ------
37 | A collection of scripts with extra features and examples is stored in the `extras` folder
38 |
39 | Code quality
40 | ------------
41 | A lot of the code is covered by tests, which also function as examples and self-explanatory documentation on usage.
42 | Check them out on the Github repo.
43 |
44 |
45 | Documentation
46 | =============
47 |
48 |
49 | .. toctree::
50 | :maxdepth: 2
51 |
52 | netwalk
53 | extras/index
54 |
--------------------------------------------------------------------------------
/docs/make.bat:
--------------------------------------------------------------------------------
1 | @ECHO OFF
2 |
3 | pushd %~dp0
4 |
5 | REM Command file for Sphinx documentation
6 |
7 | if "%SPHINXBUILD%" == "" (
8 | set SPHINXBUILD=sphinx-build
9 | )
10 | set SOURCEDIR=.
11 | set BUILDDIR=_build
12 |
13 | if "%1" == "" goto help
14 |
15 | %SPHINXBUILD% >NUL 2>NUL
16 | if errorlevel 9009 (
17 | echo.
18 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
19 | echo.installed, then set the SPHINXBUILD environment variable to point
20 | echo.to the full path of the 'sphinx-build' executable. Alternatively you
21 | echo.may add the Sphinx directory to PATH.
22 | echo.
23 | echo.If you don't have Sphinx installed, grab it from
24 | echo.https://www.sphinx-doc.org/
25 | exit /b 1
26 | )
27 |
28 | %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
29 | goto end
30 |
31 | :help
32 | %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
33 |
34 | :end
35 | popd
36 |
--------------------------------------------------------------------------------
/docs/netwalk.rst:
--------------------------------------------------------------------------------
1 | Netwalk package
2 | ===============
3 |
4 | Module contents
5 | ---------------
6 |
7 | .. automodule:: netwalk
8 | :members:
9 | :undoc-members:
10 | :show-inheritance:
11 | :private-members:
12 |
13 | Classes
14 | -------
15 |
16 | netwalk.fabric module
17 | ---------------------
18 |
19 | .. autoclass:: netwalk.fabric
20 | :members:
21 | :undoc-members:
22 | :show-inheritance:
23 | :private-members:
24 |
25 | netwalk.interface module
26 | ------------------------
27 |
28 | .. autoclass:: netwalk.interface
29 | :members:
30 | :undoc-members:
31 | :show-inheritance:
32 | :private-members:
33 |
34 | netwalk.device module
35 | ---------------------
36 |
37 | .. autoclass:: netwalk.device
38 | :members:
39 | :undoc-members:
40 | :show-inheritance:
41 | :private-members:
42 |
--------------------------------------------------------------------------------
/docs/requirements.txt:
--------------------------------------------------------------------------------
1 | sphinx-rtd-theme>=1.0.0
2 | -r ../requirements.txt
--------------------------------------------------------------------------------
/docs/usage/index.rst:
--------------------------------------------------------------------------------
1 | Data model overview
2 | ===================
3 |
4 | Netwalk defines three objects: Fabric, Switch and Interface.
5 |
6 | Fabric
7 | ------
8 |
9 | A *Fabric* describes a network of interconnected *Switches*. It can be created without parameters
10 |
11 | .. code-block:: python
12 |
13 | from netwalk import Fabric
14 | f = Fabric()
15 |
16 |
17 |
18 |
19 | A *Switch* represents a network device (and indeed should be renamed as *Device*, maybe next release?).
20 | Its
21 |
--------------------------------------------------------------------------------
/extras/discover_from_netbox/__main__.py:
--------------------------------------------------------------------------------
1 | import pickle
2 | import logging
3 | import secrets
4 | import pynetbox
5 | import netwalk
6 | from .. import import_to_netbox as nbimp
7 |
8 | logger = logging.getLogger(__name__)
9 | logger.setLevel(level=logging.DEBUG)
10 |
11 | ch = logging.StreamHandler()
12 | ch.setLevel(logging.DEBUG)
13 |
14 | logger.addHandler(ch)
15 |
16 | logging.getLogger('netwalk').setLevel(logging.INFO)
17 | logging.getLogger('netwalk').addHandler(ch)
18 |
19 | nb = pynetbox.api(
20 | secrets.NB_HOST,
21 | token=secrets.NB_API
22 | )
23 |
24 | def no_ap(nei: dict):
25 | if "ap" in nei['hostname'][4:6].lower():
26 | return False
27 | elif "axis" in nei['hostname'].lower():
28 | return False
29 | else:
30 | return True
31 |
32 |
33 |
34 | #discovered_tag = nb.extras.tags.get(name="Discovered")
35 | sites = [x for x in nb.dcim.sites.all()]
36 |
37 | for site in sites:
38 | sitename = site.slug
39 |
40 | logger.info("Connecting to %s", sitename)
41 | fabric = netwalk.Fabric()
42 | nb_devices = [x for x in nb.dcim.devices.filter(site_id=site.id, has_primary_ip=True)]
43 | #devices = [x for x in nb.dcim.devices.filter(site_id=site.id)]
44 | devices = []
45 | for i in nb_devices:
46 | if "switch" in i.device_role.name.lower():
47 | deviceipcidr = i.primary_ip.display
48 | deviceip = deviceipcidr[:deviceipcidr.index("/")]
49 | switch_object = netwalk.Device(deviceip, hostname=i.name)
50 | devices.append(switch_object)
51 |
52 | password = secrets.DATA[site.name]['password']
53 |
54 | fabric.init_from_seed_device(devices, [(secrets.USERNAME, password)], [{'secret': password, "transport": "telnet"}, {"secret": password}], 10, no_ap, scan_options={'blacklist': ['lldp_neighbors']})
55 |
56 | with open("bindata/"+site.slug+".bin", "wb") as outfile:
57 | pickle.dump(fabric, outfile)
58 |
59 | try:
60 | with open("bindata/"+site.slug+".bin", "rb") as infile:
61 | print(site.slug)
62 | fabric = pickle.load(infile)
63 | except:
64 | continue
65 |
66 | # try:
67 | #nbimp.load_fabric_object(nb, fabric, "Access Switch", sitename, True)
68 | # except Exception as e:
69 | # print(e)
70 | # pass
71 |
72 | #site.tags.append(discovered_tag)
73 | site.save()
74 |
--------------------------------------------------------------------------------
/extras/draw_network/README.md:
--------------------------------------------------------------------------------
1 | Script to generate a graph from a Fabric object.
2 | Example imports a pickled Fabric object stored in fabric_data.bin
--------------------------------------------------------------------------------
/extras/draw_network/draw_network.py:
--------------------------------------------------------------------------------
1 | """
2 | netwalk
3 | Copyright (C) 2021 NTT Ltd
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU Affero General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU Affero General Public License for more details.
14 |
15 | You should have received a copy of the GNU Affero General Public License
16 | along with this program. If not, see .
17 | """
18 |
19 | import pickle
20 | import networkx as nx
21 | from pyvis.network import Network
22 | from netwalk import Interface
23 |
24 | #matplotlib.use("Agg")
25 |
26 | with open('fabric_data.bin', 'rb') as fabricfile:
27 | fabric = pickle.load(fabricfile)
28 |
29 | g = nx.Graph()
30 |
31 | g.add_nodes_from([swdata.facts['fqdn'] for swname, swdata in fabric.devices.items()])
32 |
33 | labeldict = {y: x for x, y in fabric.devices.items()}
34 |
35 | for swname, swdata in fabric.devices.items():
36 | for intname, intdata in swdata.interfaces.items():
37 | if hasattr(intdata, 'neighbors'):
38 | if len(intdata.neighbors) == 1:
39 | if isinstance(intdata.neighbors[0], Interface):
40 | side_a = intdata.device.facts['fqdn']
41 | side_b = intdata.neighbors[0].device.facts['fqdn']
42 |
43 | #try:
44 | # assert side_a.name != "SMba32_CStellaICT"
45 | # assert side_b.name != "SMba32_CStellaICT"
46 | #except AssertionError:
47 | # continue
48 |
49 | g.add_edge(side_a, side_b)
50 |
51 |
52 |
53 |
54 | nt = Network('100%', '75%')
55 | nt.show_buttons()
56 | nt.from_nx(g)
57 | nt.show('nx.html')
--------------------------------------------------------------------------------
/extras/draw_network/requirements.txt:
--------------------------------------------------------------------------------
1 | networkx==2.5.1
--------------------------------------------------------------------------------
/extras/import_meraki_ap/import_meraki_ap.py:
--------------------------------------------------------------------------------
1 | """Kickstart netbox compilation from Meraki dashboard AP and CDP neighborship info"""
2 |
3 | import ipaddress
4 | import logging
5 | import pynetbox
6 | import meraki
7 | from slugify import slugify
8 |
9 | logger = logging.getLogger(__name__)
10 | logger.setLevel(logging.DEBUG)
11 |
12 | # Console log handler
13 | ch = logging.StreamHandler()
14 | ch.setLevel(logging.DEBUG)
15 |
16 | logger.addHandler(ch)
17 |
18 | MERAKI_API = "fgsdgfdgfdgfdsgfdgfds"
19 | MERAKI_ORG_ID = "ffdsfsfsdafdsfasf"
20 |
21 | dashboard = meraki.DashboardAPI(MERAKI_API, suppress_logging=True)
22 |
23 | nb = pynetbox.api(
24 | 'http://localhost',
25 | token='aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
26 | )
27 |
28 | nb_role = nb.dcim.device_roles.get(name="Access Point")
29 | nb_role_network = nb.dcim.device_roles.get(name="Access Switch")
30 |
31 |
32 | def create_sites():
33 | """Create site from Meraki Dashboard data"""
34 |
35 | meraki_networks = dashboard.organizations.getOrganizationNetworks(
36 | MERAKI_ORG_ID)
37 |
38 | for site in meraki_networks:
39 | logger.info('Getting site %s', site['name'])
40 | nb_site = nb.dcim.sites.get(name=site['name'])
41 |
42 | if nb_site is None:
43 | logger.info('Creating site %s', site['name'])
44 | nb_site = nb.dcim.sites.create(name=site['name'],
45 | slug=slugify(site['name']))
46 |
47 | custom_fields = {'meraki_dashboard': site['url'],
48 | 'meraki_network_id': site['id'],
49 | 'site_code': site['name'].split()[0]}
50 |
51 | if nb_site.custom_fields != custom_fields:
52 | logger.info("Updating custom fields for site %s", site['name'])
53 | nb_site.update({'custom_fields': custom_fields})
54 |
55 | # Get address from one device
56 | sitedevices = dashboard.networks.getNetworkDevices(site['id'])
57 |
58 | if len(sitedevices) > 0:
59 | device = sitedevices[0]
60 |
61 | longitude = round(float(device['lng']), 6)
62 | latitude = round(float(device['lat']), 6)
63 |
64 | try:
65 | assert nb_site.latitude == latitude
66 | assert nb_site.longitude == longitude
67 | assert nb_site.physical_address == device['address']
68 | except AssertionError:
69 | logger.info("Update geo data for site %s", site['name'])
70 | nb_site.latitude = latitude
71 | nb_site.longitude = longitude
72 | nb_site.physical_address = device['address']
73 | nb_site.save()
74 |
75 |
76 | def create_ap(access_point, modeldict):
77 | """Create Access points"""
78 |
79 | nb_device = nb.dcim.devices.get(name=access_point['name'])
80 | nb_site = nb.dcim.sites.get(cf_meraki_network_id=access_point['networkId'])
81 | assert nb_site is not None
82 |
83 | if nb_device is None:
84 | try:
85 | nb_model = modeldict[access_point['model']]
86 | except KeyError:
87 | nb_model = nb.dcim.device_types.get(model=access_point['model'])
88 | assert nb_model is not None, f"Model {access_point['model']} not found, create by hand"
89 | modeldict[access_point['model']] = nb_model
90 |
91 | logger.info("Creating device %s", access_point['name'])
92 | nb_device = nb.dcim.devices.create(name=access_point['name'],
93 | device_type=modeldict[access_point['model']].id,
94 | site=nb_site.id,
95 | device_role=nb_role.id,
96 | serial=access_point['serial'])
97 |
98 | else:
99 | # Check serial number is the same otherwise could be a device with the same name
100 | try:
101 | assert nb_device.serial == access_point['serial']
102 | except AssertionError:
103 | try:
104 | nb_model = modeldict[access_point['model']]
105 | except KeyError:
106 | nb_model = nb.dcim.device_types.get(
107 | model=access_point['model'])
108 | modeldict[access_point['model']] = nb_model
109 |
110 | nb_device = nb.dcim.devices.get(
111 | name=f"{access_point['name']}-{access_point['serial']}")
112 | if nb_device is None:
113 | logger.info("Creating device %s%s",
114 | access_point['name'], access_point['serial'])
115 | nb_device = nb.dcim.devices.create(name=f"{access_point['name']}-{access_point['serial']}",
116 | device_type=nb_model.id,
117 | site=nb_site.id,
118 | device_role=nb_role.id,
119 | serial=access_point['serial'])
120 |
121 | return nb_device, nb_site
122 |
123 |
124 | def create_mgmt_interface(access_point, nb_device, nb_site):
125 | """Create fake management interfaces for cdp neighbors"""
126 |
127 | logger.info('Get management interface data for %s', access_point['serial'])
128 | mgmt = dashboard.devices.getDeviceManagementInterface(
129 | access_point['serial'])
130 |
131 | nb_interface = nb.dcim.interfaces.get(device_id=nb_device.id)
132 | nb_interface.mac_address = access_point['mac']
133 | nb_interface.save()
134 |
135 | try:
136 | assert 'staticIp' in mgmt['wan1'], "AP in DHCP"
137 | ipadd = ipaddress.ip_interface(
138 | f"{mgmt['wan1']['staticIp']}/{mgmt['wan1']['staticSubnetMask']}")
139 | except (KeyError, AssertionError) as e:
140 | logger.warning("%s", e)
141 | raise e
142 |
143 | try:
144 | ip = nb.ipam.ip_addresses.create(address=str(ipadd),
145 | assigned_object_id=nb_interface.id,
146 | assigned_object_type="dcim.interface")
147 |
148 | logger.info("Created IP %s and assigned to interface %s",
149 | mgmt['wan1']['staticIp'], nb_interface.name)
150 | except pynetbox.RequestError:
151 | ip = nb.ipam.ip_addresses.get(address=str(ipadd))
152 |
153 | # Check prefix esists
154 | if len(nb.ipam.prefixes.filter(q=ip.address)) == 0:
155 | print("Creating prefix "+str(ipadd.network))
156 | nb_prefix = nb.ipam.prefixes.create(prefix=str(ipadd.network),
157 | status="active",
158 | site=nb_site.id)
159 |
160 | dash_url = dashboard.devices.getDevice(access_point['serial'])['url']
161 | try:
162 | assert nb_device.primary_ip4 == ip
163 | except AssertionError:
164 | try:
165 | nb_device.primary_ip4 = ip
166 | nb_device.custom_fields.update({'management_page': dash_url})
167 | nb_device.save()
168 | logger.info("Added IP %s as primary for device %s",
169 | ip, nb_device.name)
170 | except pynetbox.RequestError as err:
171 | logger.warning("%s", err)
172 | raise err
173 |
174 | return nb_interface
175 |
176 |
177 | def create_cdp_nei(access_point, nb_site):
178 | """Create devices from cdp neighborship data"""
179 |
180 | neighdata = dashboard.devices.getDeviceLldpCdp(access_point['serial'])
181 |
182 | try:
183 | neigh = neighdata['ports']['wired0']['cdp']
184 | except KeyError as e:
185 | logger.warning("Device %s has no neighbors", access_point['name'])
186 | raise e
187 |
188 | neigh_port = nb.dcim.interfaces.get(name=neigh['portId'],
189 | device=neigh['deviceId'])
190 |
191 | neigh_sw = nb.dcim.devices.get(
192 | name=neigh['deviceId'])
193 | if neigh_port is None:
194 | if neigh_sw is None:
195 | print("Creating device "+neigh['deviceId'])
196 | neigh_sw = nb.dcim.devices.create(name=neigh['deviceId'],
197 | device_type=1,
198 | site=nb_site.id,
199 | device_role=nb_role_network.id,
200 | )
201 |
202 | prefix = nb.ipam.prefixes.get(q=neigh['address'])
203 | if prefix is None:
204 | prefix = "0.0.0.0/32"
205 | try:
206 | svi = nb.dcim.interfaces.get(device_id=neigh_sw.id)
207 | except ValueError:
208 | svi = list(nb.dcim.interfaces.filter(device_id=neigh_sw.id))[0]
209 |
210 | porttype = "100base-tx" if "Fast" in neigh['portId'] else "1000base-t"
211 |
212 | print("Creating port "+neigh['portId']+" on device "+neigh_sw.name)
213 | neigh_port = nb.dcim.interfaces.create(device=neigh_sw.id,
214 | name=neigh['portId'],
215 | type=porttype,
216 | )
217 |
218 | if svi is None:
219 | svi = neigh_port
220 |
221 | prefix = nb.ipam.prefixes.get(q=neigh['address'])
222 |
223 | try:
224 | svi = nb.dcim.interfaces.get(device_id=neigh_sw.id)
225 | except ValueError:
226 | svi = list(nb.dcim.interfaces.filter(device_id=neigh_sw.id))[0]
227 |
228 | if svi is None:
229 | svi = neigh_port
230 |
231 | if prefix is None:
232 | prefix = "0.0.0.0/32"
233 |
234 | nb_address = nb.ipam.ip_addresses.get(
235 | address=f"{neigh['address']}/{str(prefix).split('/')[1]}")
236 |
237 | neigh_sw = nb.dcim.devices.get(
238 | name=neigh['deviceId'])
239 |
240 | if nb_address is not None:
241 | assert nb_address.assigned_object.device == neigh_sw, "IP found on more than one device"
242 | else:
243 | nb_address = nb.ipam.ip_addresses.create(
244 | address=f"{neigh['address']}/{str(prefix).split('/')[1]}",
245 | assigned_object_id=svi.id,
246 | assigned_object_type="dcim.interface"
247 | )
248 |
249 | if neigh_sw.primary_ip4 != nb_address:
250 | neigh_sw.primary_ip4 = nb_address
251 | logger.info("Updating primary IP for device %s %s",
252 | neigh_sw.name, nb_address)
253 | neigh_sw.save()
254 |
255 | return neigh_port
256 |
257 |
258 | def create_devices():
259 | """Create devices from meraki dashboard information"""
260 |
261 | meraki_inventory = list(
262 | dashboard.organizations.getOrganizationInventoryDevices(MERAKI_ORG_ID, -1))
263 |
264 | modeldict = {}
265 | for pos, ap in enumerate(meraki_inventory):
266 | logger.info("Device %s out of %s", pos, len(meraki_inventory)-1)
267 |
268 | if ap['networkId'] is None:
269 | continue
270 |
271 | nb_device, nb_site = create_ap(ap, modeldict)
272 |
273 | try:
274 | nb_interface = create_mgmt_interface(ap, nb_device, nb_site)
275 | except (KeyError, pynetbox.RequestError, AssertionError) as e:
276 | continue
277 |
278 | try:
279 | neigh_port = create_cdp_nei(ap, nb_site)
280 | except KeyError:
281 | continue
282 |
283 | logger.info("Connecting AP %s to device %s on %s",
284 | nb_interface.device.name, neigh_port.device.name, neigh_port.name)
285 | try:
286 | cable = nb.dcim.cables.create(termination_a_type="dcim.interface",
287 | termination_b_type="dcim.interface",
288 | termination_a_id=nb_interface.id,
289 | termination_b_id=neigh_port.id)
290 | except pynetbox.core.query.RequestError as e:
291 | logger.info("%s", e)
292 | continue
293 |
294 |
295 | def main():
296 | """Main"""
297 | create_sites()
298 | create_devices()
299 |
300 |
301 | if __name__ == '__main__':
302 | main()
303 |
--------------------------------------------------------------------------------
/extras/import_to_netbox/README.md:
--------------------------------------------------------------------------------
1 | Cycle through a list of .bin files under bindata/ and upload their data to Netbox
2 |
3 | Currently generates:
4 |
5 | * VLANs
6 | * Switches
7 | * Interfaces
8 | * IPs and prefixes
9 | * Assigns IPs to interfaces
10 | * Cables between switches
--------------------------------------------------------------------------------
/extras/import_to_netbox/requirements.txt:
--------------------------------------------------------------------------------
1 | pynetbox
2 | python-slugify
--------------------------------------------------------------------------------
/netwalk/__init__.py:
--------------------------------------------------------------------------------
1 | "Main file for library"
2 |
3 | #pylint: disable=wrong-import-order
4 | from .device import Device, Switch
5 | from .fabric import Fabric
6 | from .interface import Interface
7 |
8 | __all__ = ["Interface", "Switch", "Fabric", "Device"]
9 |
10 |
11 | # Taken from requests library, check their documentation
12 | import logging
13 | from logging import NullHandler
14 |
15 | logging.getLogger(__name__).addHandler(NullHandler())
16 |
--------------------------------------------------------------------------------
/netwalk/device.py:
--------------------------------------------------------------------------------
1 | """
2 | netwalk
3 | Copyright (C) 2021 NTT Ltd
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU Affero General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU Affero General Public License for more details.
14 |
15 | You should have received a copy of the GNU Affero General Public License
16 | along with this program. If not, see .
17 | """
18 |
19 | import datetime
20 | import ipaddress
21 | import logging
22 | import os
23 | from typing import Dict, List, Optional, Union
24 |
25 | import napalm
26 | import textfsm
27 | from ciscoconfparse import CiscoConfParse
28 | from netaddr import EUI
29 |
30 | from netwalk.interface import Interface
31 | from netwalk.libs import interface_name_expander
32 |
33 |
34 | class Device():
35 | "Device type"
36 | hostname: str
37 | #: Dict of {name: Interface}
38 | interfaces: Dict[str, 'Interface']
39 | discovery_status: Optional[Union[str, datetime.datetime]]
40 | fabric: 'Fabric'
41 | mgmt_address: Union[ipaddress.ip_address, str]
42 | facts: dict
43 |
44 | def __init__(self, mgmt_address, **kwargs) -> None:
45 | if isinstance(mgmt_address, str):
46 | try:
47 | self.mgmt_address = ipaddress.ip_address(mgmt_address)
48 | except ValueError:
49 | self.mgmt_address = None
50 | else:
51 | self.mgmt_address = mgmt_address
52 |
53 | self.hostname: str = kwargs.get('hostname', mgmt_address)
54 | self.interfaces: Dict[str, 'Interface'] = kwargs.get('interfaces', {})
55 | self.discovery_status = kwargs.get('discovery_status', None)
56 | self.fabric: 'Fabric' = kwargs.get('fabric', None)
57 | self.facts: dict = kwargs.get('facts', None)
58 | if self.hostname is None:
59 | self.logger = logging.getLogger(__name__ + str(self.mgmt_address))
60 | else:
61 | self.logger = logging.getLogger(__name__ + self.hostname)
62 |
63 | if self.fabric is not None:
64 | if self.hostname is None:
65 | self.fabric.devices[str(self.mgmt_address)] = self
66 | else:
67 | self.fabric.devices[self.hostname] = self
68 |
69 | def add_interface(self, intobject: Interface):
70 | """Add interface to device
71 |
72 | :param intobject: Interface to add
73 | :type intobject: netwalk.Interface
74 | """
75 | intobject.device = self
76 | self.interfaces[intobject.name] = intobject
77 |
78 | if type(self) == Switch:
79 | for _, v in self.interfaces.items():
80 | v.parse_config(second_pass=True)
81 |
82 | def promote_to_switch(self):
83 | self.__class__ = Switch
84 | self.__init__(mgmt_address=self.mgmt_address,
85 | hostname=self.hostname,
86 | interfaces=self.interfaces,
87 | discovery_status=self.discovery_status,
88 | fabric=self.fabric,
89 | facts=self.facts)
90 |
91 |
92 | class Switch(Device):
93 | """
94 | Switch object to hold data
95 | Initialize with name and hostname, call retrieve_data()
96 | to connect to device and retrieve automaticlly or
97 | pass config as string to parse locally
98 | """
99 |
100 | INTERFACE_TYPES = r"([Pp]ort-channel|\w*Ethernet|\w*GigE|Vlan|Loopback)."
101 | INTERFACE_FILTER = r"^interface " + INTERFACE_TYPES
102 |
103 | logger: logging.Logger
104 | hostname: str
105 | #: Dict of {name: Interface}
106 | interfaces: Dict[str, Interface]
107 | #: Pass at init time to parse config automatically
108 | config: Optional[str]
109 | napalm_optional_args: dict
110 | #: Time of object initialization. All timers will be calculated from it
111 | inventory: List[Dict[str, Dict[str, str]]]
112 | vtp: Optional[str]
113 | arp_table: Dict[ipaddress.IPv4Interface, dict]
114 | interfaces_ip: dict
115 | vlans: Optional[Dict[int, dict]]
116 | vlans_set: set
117 | local_admins: Optional[Dict[str, dict]]
118 | timeout: int
119 | mac_table: dict
120 |
121 | def __init__(self,
122 | mgmt_address,
123 | **kwargs):
124 |
125 | super().__init__(mgmt_address, **kwargs)
126 | self.config: Optional[str] = kwargs.get('config', None)
127 | self.napalm_optional_args = kwargs.get('napalm_optional_args', None)
128 | self.vtp: Optional[str] = None
129 | self.arp_table: Dict[ipaddress.IPv4Interface, dict] = {}
130 | self.interfaces_ip = {}
131 | self.vlans: Optional[Dict[int, dict]] = None
132 | # VLANs configured on the switch
133 | self.vlans_set = {x for x in range(1, 4095)}
134 | self.local_admins: Optional[Dict[str, dict]] = None
135 | self.timeout = 30
136 | self.mac_table = {}
137 | self.platform = kwargs.get('platfomr', 'ios')
138 |
139 | if self.config is not None:
140 | self._parse_config()
141 |
142 | def retrieve_data(self,
143 | username: str,
144 | password: str,
145 | napalm_optional_args: dict = None,
146 | scan_options: dict = None):
147 | """
148 | One-stop function to get data from switch.
149 |
150 | :param username: username
151 | :type username: str
152 | :param password: password
153 | :type password: str
154 | :param napalm_optional_args: Refer to Napalm's documentation
155 | :type napalm_optional_args: dict
156 | :param scan_options: Valid keys are 'whitelist' and 'blacklist'. Value must be a list of options to pass to _get_switch_data
157 | :type scan_options: dict(str, list(str))
158 | """
159 |
160 | self.napalm_optional_args = {} if napalm_optional_args is None else napalm_optional_args
161 | scan_options = {} if scan_options is None else scan_options
162 |
163 | self.connect(username, password, napalm_optional_args)
164 | try:
165 | self._get_switch_data(**scan_options)
166 | except Exception as e:
167 | self.session.close()
168 | raise e
169 |
170 | else:
171 | self.session.close()
172 |
173 | def connect(self, username: str, password: str, napalm_optional_args: dict = None) -> None:
174 | """Connect to device
175 |
176 | :param username: username
177 | :type username: str
178 | :param password: password
179 | :type password: str
180 | :param napalm_optional_args: Check Napalm's documentation about optional-args, defaults to None
181 | :type napalm_optional_args: dict, optional
182 | """
183 | driver = napalm.get_network_driver(self.platform)
184 |
185 | if napalm_optional_args is not None:
186 | self.napalm_optional_args = napalm_optional_args
187 |
188 | self.session = driver(str(self.mgmt_address),
189 | username=username,
190 | password=password,
191 | timeout=self.timeout,
192 | optional_args=self.napalm_optional_args)
193 |
194 | self.logger.info("Connecting to %s", self.mgmt_address)
195 | self.session.open()
196 |
197 | def get_active_vlans(self):
198 | """Get active vlans from switch.
199 | Only lists vlans configured on ports
200 |
201 | :return: [description]
202 | :rtype: [type]
203 | """
204 | vlans = set([1])
205 | for _, intdata in self.interfaces.items():
206 | vlans.add(intdata.native_vlan)
207 | try:
208 | if len(intdata.allowed_vlan) != 4094:
209 | vlans = vlans.union(intdata.allowed_vlan)
210 | except (AttributeError, TypeError):
211 | continue
212 |
213 | # Find trunk interfaces with no neighbors
214 | noneightrunks = []
215 | for intdata in self.interfaces.values():
216 | if intdata.mode == "trunk":
217 | try:
218 | assert not isinstance(intdata.neighbors[0], Interface)
219 | except (IndexError, AssertionError, AttributeError):
220 | # Interface has explicit neighbor, exclude
221 | continue
222 |
223 | noneightrunks.append(intdata)
224 |
225 | # Find if interface has mac addresses
226 | activevlans = set()
227 | for macdata in self.mac_table.values():
228 | if macdata['interface'] == intdata:
229 | activevlans.add(macdata['vlan'])
230 |
231 | vlans = vlans.union(activevlans)
232 |
233 | # Add vlans with layer3 configured
234 | for intdata in self.interfaces.values():
235 | if "vlan" in intdata.name.lower():
236 | if intdata.is_enabled:
237 | vlanid = int(intdata.name.lower().replace("vlan", ""))
238 | vlans.add(vlanid)
239 |
240 | # Remove vlans not explicitly configured
241 | vlans.intersection_update(self.vlans_set)
242 | return vlans
243 |
244 | def _parse_config(self):
245 | """Parse show run
246 | """
247 | if isinstance(self.config, str):
248 | parsed_conf = CiscoConfParse(self.config.split("\n"))
249 | interface_config_list: list = parsed_conf.find_objects(
250 | self.INTERFACE_FILTER)
251 |
252 | for intf in interface_config_list:
253 | thisint = Interface(config=intf.ioscfg)
254 | localint = self.interfaces.get(thisint.name, None)
255 | if localint is not None:
256 | localint.config = intf.ioscfg
257 | localint.parse_config()
258 | else:
259 | thisint.parse_config()
260 | self.add_interface(thisint)
261 |
262 | else:
263 | TypeError("No interface loaded, cannot parse")
264 |
265 | def _get_switch_data(self,
266 | whitelist: Optional[List[str]] = None,
267 | blacklist: Optional[List[str]] = None):
268 | """
269 | Get data from switch.
270 | If no argument is passed, scan all modules
271 |
272 | :param whitelist: List of modules to scan, defaults to None
273 | :type whitelist: list(str)
274 | :param blacklist: List of modules to exclude from scan, defaults to None
275 | :type blacklist: list(str)
276 |
277 | Either whitelist or blacklist can be passed.
278 | If both are passed, whitelist takes precedence over blacklist.
279 |
280 | Valid values are:
281 | - 'mac_address'
282 | - 'interface_status'
283 | - 'cdp_neighbors'
284 | - 'lldp_neighbors'
285 | - 'vtp'
286 | - 'vlans'
287 | - 'l3_int'
288 | - 'local_admins'
289 | - 'inventory'
290 |
291 | Running config is ALWAYS returned
292 | """
293 |
294 | allscans = ['mac_address', 'interface_status',
295 | 'cdp_neighbors', 'lldp_neighbors', 'vtp', 'vlans', 'l3_int', 'local_admins', 'inventory']
296 | scan_to_perform = []
297 |
298 | if whitelist is not None:
299 | for i in whitelist:
300 | assert i in allscans, "Parameter not recognised in scan list. has to be any of ['mac_address', 'interface_status', 'cdp_neighbors', 'lldp_neighbors', 'vtp', 'vlans', 'l3_int', 'local_admins', 'inventory']"
301 |
302 | scan_to_perform = whitelist
303 |
304 | elif blacklist is not None:
305 | scan_to_perform = allscans
306 | for i in blacklist:
307 | assert i in allscans, "Parameter not recognised in scan list. has to be any of ['mac_address', 'interface_status', 'cdp_neighbors', 'lldp_neighbors', 'vtp', 'vlans', 'l3_int', 'local_admins', 'inventory']"
308 | scan_to_perform.remove(i)
309 |
310 | else:
311 | scan_to_perform = allscans
312 |
313 | self.facts = self.session.get_facts()
314 |
315 | try:
316 | self.hostname = self.facts['fqdn'].replace(
317 | ".not set", "") if self.facts['fqdn'] != 'Unknown' else self.facts['hostname']
318 | except KeyError:
319 | pass
320 |
321 | self.init_time = datetime.datetime.now()
322 |
323 | self.config = self.session.get_config(retrieve="running")['running']
324 |
325 | self._parse_config()
326 |
327 | if 'mac_address' in scan_to_perform:
328 | # Get mac address table
329 | self.mac_table = {} # Clear before adding new data
330 | mactable = self.session.get_mac_address_table()
331 |
332 | macdict = {EUI(x['mac']): x for x in mactable}
333 |
334 | for k, v in macdict.items():
335 | if v['interface'] == '':
336 | continue
337 |
338 | v['interface'] = interface_name_expander(v['interface'])
339 |
340 | v.pop('mac')
341 | v.pop('static')
342 | v.pop('moves')
343 | v.pop('last_move')
344 | v.pop('active')
345 |
346 | try:
347 | # some interfaces have diFFeRenT capitalization across outputs
348 | v['interface'] = {k.lower(): v for k, v in self.interfaces.items()}[
349 | v['interface'].lower()]
350 | self.mac_table[k] = v
351 | except KeyError:
352 | # print("Interface {} not found".format(v['interface']))
353 | continue
354 |
355 | # Count macs per interface
356 | for _, data in self.mac_table.items():
357 | try:
358 | data['interface'].mac_count += 1
359 | except KeyError:
360 | pass
361 |
362 | if 'interface_status' in scan_to_perform:
363 | # Get interface status
364 | self._parse_show_interface()
365 |
366 | if 'cdp_neighbors' in scan_to_perform:
367 | self._parse_cdp_neighbors()
368 |
369 | if 'lldp_neighbors' in scan_to_perform:
370 | self._parse_lldp_neighbors()
371 |
372 | if 'vtp' in scan_to_perform:
373 | # Get VTP status
374 | command = "show vtp status"
375 | result = self.session.cli([command])
376 |
377 | self.vtp = result[command]
378 |
379 | if 'vlans' in scan_to_perform:
380 | # Get VLANs
381 | self.vlans = self.session.get_vlans()
382 | self.vlans_set = set([int(k) for k, v in self.vlans.items()])
383 |
384 | if 'l3_int' in scan_to_perform:
385 | # Get l3 interfaces
386 | self.interfaces_ip = self.session.get_interfaces_ip()
387 | self.arp_table = self.session.get_arp_table()
388 |
389 | if 'local_admins' in scan_to_perform:
390 | # Get local admins
391 | self.local_admins = self.session.get_users()
392 |
393 | if 'inventory' in scan_to_perform:
394 | # Get inventory
395 | self.inventory = self._parse_inventory()
396 |
397 | def _parse_inventory(self):
398 | command = "show inventory"
399 | showinventory = self.session.cli([command])[command]
400 |
401 | fsmpath = os.path.dirname(os.path.realpath(
402 | __file__)) + "/textfsm_templates/show_inventory.textfsm"
403 | with open(fsmpath, 'r') as fsmfile:
404 | try:
405 | re_table = textfsm.TextFSM(fsmfile)
406 | fsm_results = re_table.ParseTextToDicts(showinventory)
407 | except Exception as e:
408 | self.logger.error("Textfsm parsing error %s", e)
409 | return {}
410 |
411 | result = {}
412 | for i in fsm_results:
413 | result[i['name']] = {'descr': i['descr'],
414 | 'pid': i['pid'],
415 | 'vid': i['vid'],
416 | 'sn': i['sn'],
417 | }
418 |
419 | return result
420 |
421 | def _parse_show_interface(self):
422 | """Parse output of show inteface with greater data collection than napalm"""
423 | self.session.device.write_channel("show interface")
424 | self.session.device.write_channel("\n")
425 | self.session.device.timeout = 30 # Could take ages...
426 | showint = self.session.device.read_until_prompt(max_loops=3000)
427 | fsmpath = os.path.dirname(os.path.realpath(
428 | __file__)) + "/textfsm_templates/show_interface.textfsm"
429 | with open(fsmpath, 'r') as fsmfile:
430 | try:
431 | re_table = textfsm.TextFSM(fsmfile)
432 | fsm_results = re_table.ParseTextToDicts(showint)
433 | except Exception as e:
434 | self.logger.error("Show interface parsing failed %s", e)
435 | return None
436 |
437 | for intf in fsm_results:
438 | if intf['name'] in self.interfaces:
439 | for k, v in intf.items():
440 | if k in ('last_in', 'last_out', 'last_out_hang', 'last_clearing'):
441 | val = self._cisco_time_to_dt(v)
442 | setattr(self.interfaces[intf['name']], k, val)
443 | self.logger.debug(
444 | "Set attribute %s to %s for %s", k, val, intf['name'])
445 | elif k == 'is_enabled':
446 | val = False if 'administratively' in v else True
447 | setattr(self.interfaces[intf['name']], k, val)
448 | self.logger.debug(
449 | "Set attribute %s to %s, parsed value: %s for %s", k, val, v, intf['name'])
450 | elif k == 'is_up':
451 | val = True if 'up' in v else False
452 | setattr(self.interfaces[intf['name']], k, val)
453 | setattr(
454 | self.interfaces[intf['name']], 'protocol_status', v)
455 | self.logger.debug(
456 | "Set attribute %s to %s, parsed value: %s for %s", k, val, v, intf['name'])
457 | else:
458 | setattr(self.interfaces[intf['name']], k, v)
459 | self.logger.debug(
460 | "Set attribute %s to %s for %s", k, v, intf['name'])
461 | else:
462 | # Sometimes multi-type interfaces appear in one command and not in another
463 | newint = Interface(name=intf['name'])
464 | self.add_interface(newint)
465 | self.logger.info(
466 | "Creating new interface %s not found previously", intf['name'])
467 |
468 | def _parse_cdp_neighbors(self):
469 | """Ask for and parse CDP neighbors"""
470 | self.session.device.write_channel("show cdp neigh detail")
471 | self.session.device.write_channel("\n")
472 | self.session.device.timeout = 30 # Could take ages...
473 | neighdetail = self.session.device.read_until_prompt(max_loops=3000)
474 | fsmpath = os.path.dirname(os.path.realpath(
475 | __file__)) + "/textfsm_templates/show_cdp_neigh_detail.textfsm"
476 | with open(fsmpath, 'r') as fsmfile:
477 | try:
478 | re_table = textfsm.TextFSM(fsmfile)
479 | fsm_results = re_table.ParseTextToDicts(neighdetail)
480 | except Exception as e:
481 | self.logger.error("Show cdp neighbor parsing failed %s", e)
482 | return None
483 |
484 | for result in fsm_results:
485 | self.logger.debug("Found CDP neighbor %s IP %s local int %s, remote int %s",
486 | result['dest_host'], result['mgmt_ip'], result['local_port'], result['remote_port'])
487 |
488 | for nei in fsm_results:
489 | try:
490 | address = ipaddress.ip_address(nei['mgmt_ip'])
491 | except ValueError:
492 | address = None
493 |
494 | neigh_data = {'hostname': nei['dest_host'],
495 | 'ip': address,
496 | 'platform': nei['platform'],
497 | 'remote_int': nei['remote_port']
498 | }
499 |
500 | self.interfaces[nei['local_port']].neighbors.append(neigh_data)
501 |
502 | def _parse_lldp_neighbors(self):
503 | """Ask for and parse LLDP neighbors"""
504 | self.session.device.write_channel("show lldp neigh detail")
505 | self.session.device.write_channel("\n")
506 | self.session.device.timeout = 30 # Could take ages...
507 | neighdetail = self.session.device.read_until_prompt(max_loops=3000)
508 |
509 | fsmpath = os.path.dirname(os.path.realpath(
510 | __file__)) + "/textfsm_templates/show_lldp_neigh_detail.textfsm"
511 | with open(fsmpath, 'r') as fsmfile:
512 | try:
513 | re_table = textfsm.TextFSM(fsmfile)
514 | fsm_results = re_table.ParseTextToDicts(neighdetail)
515 | except Exception as e:
516 | self.logger.error("Show lldp neighbor parsing failed %s", e)
517 | return None
518 |
519 | for result in fsm_results:
520 | self.logger.debug("Found LLDP neighbor %s IP %s local int %s, remote int %s",
521 | result['neighbor'], result['mgmt_ip'], result['local_port'], result['remote_port'])
522 |
523 | for nei in fsm_results:
524 | try:
525 | address = ipaddress.ip_address(nei['mgmt_ip'])
526 | except ValueError:
527 | address = None
528 | continue
529 |
530 | if nei['local_port'] == '':
531 | continue
532 |
533 | # No hostname
534 | if nei['neighbor'] == '':
535 | continue
536 |
537 | neigh_data = {'hostname': nei['neighbor'],
538 | 'ip': address,
539 | 'platform': nei['system_description'],
540 | 'remote_int': nei['remote_port_id']
541 | }
542 |
543 | self.interfaces[interface_name_expander(
544 | nei['local_port'])].neighbors.append(neigh_data)
545 |
546 | def _cisco_time_to_dt(self, time: str) -> datetime.datetime:
547 | """Converts time from now to absolute, starting when Switch object was initialised
548 |
549 | :param time: Cisco diff time (e.g. '00:00:01' or '5w4d')
550 | :param type: str
551 |
552 | :return: Absolute time
553 | :rtype: datetime.datetime
554 | """
555 | weeks = 0
556 | days = 0
557 | hours = 0
558 | minutes = 0
559 | seconds = 0
560 |
561 | if time == 'never' or time == '':
562 | # TODO: return uptime
563 | return datetime.datetime(1970, 1, 1, 0, 0, 0)
564 |
565 | if ':' in time:
566 | hours, minutes, seconds = time.split(':')
567 | hours = int(hours)
568 | minutes = int(minutes)
569 | seconds = int(seconds)
570 |
571 | elif 'y' in time:
572 | # 2y34w
573 | years, weeks = time.split('y')
574 | weeks = weeks.replace('w', '')
575 | years = int(years)
576 | weeks = int(weeks)
577 |
578 | weeks = years*54 + weeks
579 |
580 | elif 'h' in time:
581 | # 3d05h
582 | days, hours = time.split('d')
583 | hours = hours.replace('h', '')
584 |
585 | days = int(days)
586 | hours = int(hours)
587 |
588 | else:
589 | # 24w2d
590 | weeks, days = time.split('w')
591 | days = days.replace('d', '')
592 |
593 | weeks = int(weeks)
594 | days = int(days)
595 |
596 | delta = datetime.timedelta(weeks=weeks, days=days, hours=hours,
597 | minutes=minutes, seconds=seconds)
598 |
599 | return self.init_time - delta
600 |
601 | def __str__(self):
602 | """Return switch config from hostname and interfaces
603 |
604 | :return: Switch "show run" from internal data
605 | :rtype: str"""
606 | showrun = f"! {self.hostname}"
607 |
608 | try:
609 | showrun = showrun + f" {self.hostname}\n"
610 | except (AttributeError, KeyError):
611 | showrun = showrun + "\n"
612 |
613 | showrun = showrun + "!\n"
614 |
615 | for intname, intdata in self.interfaces.items():
616 | showrun = showrun + str(intdata)
617 |
618 | return showrun
619 |
--------------------------------------------------------------------------------
/netwalk/fabric.py:
--------------------------------------------------------------------------------
1 | """
2 | netwalk
3 | Copyright (C) 2021 NTT Ltd
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU Affero General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU Affero General Public License for more details.
14 |
15 | You should have received a copy of the GNU Affero General Public License
16 | along with this program. If not, see .
17 | """
18 |
19 | import concurrent.futures
20 | import ipaddress
21 | import logging
22 | from datetime import datetime as dt
23 | from socket import timeout as socket_timeout
24 | from typing import Any, Dict
25 |
26 | from napalm.base.exceptions import ConnectionException
27 | from netaddr import EUI
28 |
29 | from netwalk.device import Device, Switch
30 | from netwalk.interface import Interface
31 |
32 |
33 | class Fabric():
34 | """Defines a fabric, i.e. a graph of connected Devices and their global
35 | mac address table
36 |
37 | """
38 | logger: logging.Logger
39 | #: A dictionary of {hostname: Switch}
40 | switches: Dict[str, Switch]
41 |
42 | # TODO: Dict value can be either str or dt, fix
43 | #: Dictionary of {hostname: status} where status can be "Queued", "Failed" or a datetime of when the discovery was completed.
44 | #: It is set and used by init_from_seed_device()
45 | discovery_status: Dict[str, Any]
46 |
47 | #: Calculated global mac address table across all switches in the fabric.
48 | #: Generated by _recalculate_macs().
49 | #: Dictionary of {netaddr.EUI (mac address object): attribute_dictionary}. Contains pointer to Interface object where the mac is.
50 | mac_table: Dict[EUI, dict]
51 |
52 | def __init__(self):
53 | """Init module"""
54 | self.logger = logging.getLogger(__name__)
55 | self.devices = {}
56 | self.discovery_status = {}
57 | self.mac_table = {}
58 |
59 | def add_device(self,
60 | switch: Switch,
61 | credentials,
62 | napalm_optional_args=None,
63 | **kwargs):
64 | """
65 | Try to connect to, and if successful add to fabric, a new Device object
66 |
67 | :param host: IP or hostname of device to connect to
68 | :type host: str
69 | :param credentials: List of (username, password) tuples to try
70 | :type credentials: list(tuple(str,str))
71 | :param napalm_optional_args: Optional_args to pass to NAPALM, as many as you want
72 | :type napalm_optional_args: list(dict)
73 | """
74 |
75 | if napalm_optional_args is None:
76 | napalm_optional_args = [None]
77 |
78 | assert isinstance(switch, Device)
79 |
80 | self.discovery_status[switch.mgmt_address] = "Queued"
81 | switch.promote_to_switch()
82 |
83 | # Check if Switch is already in fabric.
84 | # Hostname is not enough because CDP stops at 40 characters and it might have been added
85 | # with a cut-off hostname
86 | if switch.hostname[:40] in self.devices:
87 | return switch
88 | else:
89 | self.devices[switch.hostname[:40]] = switch
90 |
91 | self.logger.info("Creating switch %s", switch.mgmt_address)
92 | connected = False
93 | for optional_arg in napalm_optional_args:
94 | if connected:
95 | break
96 |
97 | for cred in credentials:
98 | try:
99 | switch.retrieve_data(cred[0], cred[1],
100 | napalm_optional_args=optional_arg)
101 | connected = True
102 | self.logger.info(
103 | "Connection to switch %s successful", switch.mgmt_address)
104 | break
105 | except (ConnectionException, ConnectionRefusedError, socket_timeout):
106 | self.logger.warning(
107 | "Login failed, trying next method if available")
108 | continue
109 |
110 | if not connected:
111 | self.logger.error(
112 | "Could not login with any of the specified methods")
113 | raise ConnectionError(
114 | "Could not log in with any of the specified methods")
115 |
116 | self.logger.info("Finished discovery of switch %s",
117 | switch.hostname)
118 |
119 | return switch
120 |
121 | def init_from_seed_device(self,
122 | seed_hosts: str,
123 | credentials: list,
124 | napalm_optional_args=None,
125 | parallel_threads=1,
126 | neigh_validator_callback=None):
127 | """
128 | Initialise entire fabric from a seed device.
129 |
130 | :param seed_hosts: List of IP or hostname of seed devices
131 | :type seed_hosts: str
132 | :param credentials: List of (username, password) tuples to try
133 | :type credentials: list
134 | :param napalm_optional_args: Optional_args to pass to NAPALM for telnet
135 | :type napalm_optional_args: list(dict(str, str)), optional
136 | :param neigh_validator_callback: Function accepting a Device object. Return True if device should be actively discovered
137 | :type neigh_validator_callback: function
138 | """
139 |
140 | if napalm_optional_args is None:
141 | napalm_optional_args = [None]
142 |
143 | for i in seed_hosts:
144 | if isinstance(i, Device):
145 | self.discovery_status[i.mgmt_address] = "Queued"
146 | else:
147 | self.discovery_status[ipaddress.ip_address(i)] = "Queued"
148 |
149 | # We can use a with statement to ensure threads are cleaned up promptly
150 | with concurrent.futures.ThreadPoolExecutor(max_workers=parallel_threads) as executor:
151 | # Start the load operations and mark each future with its URL
152 | self.logger.debug("Adding seed hosts to loop")
153 |
154 | future_switch_data = {}
155 | for i in seed_hosts:
156 | if isinstance(i, Device):
157 | switch = i
158 | else:
159 | switch = Device(i)
160 |
161 | key = executor.submit(
162 | self.add_device,
163 | switch,
164 | credentials,
165 | napalm_optional_args,
166 | discovery_status="Queued")
167 |
168 | value = i
169 |
170 | future_switch_data[key] = value
171 |
172 | while future_switch_data:
173 | self.logger.info(
174 | "Connecting to switches, %d to go", len(future_switch_data))
175 | done, _ = concurrent.futures.wait(future_switch_data,
176 | return_when=concurrent.futures.FIRST_COMPLETED)
177 |
178 | for fut in done:
179 | hostname = future_switch_data.pop(fut)
180 | self.logger.debug("Got data for %s", hostname)
181 | try:
182 | swobject = None
183 | swdata = None
184 | swobject = fut.result()
185 | except Exception as exc:
186 | # raise exc
187 |
188 | self.logger.error(
189 | '%r generated an exception: %s', hostname, exc)
190 | self.discovery_status[hostname] = "Failed"
191 |
192 | if hostname == "":
193 | # all hope is lost
194 | continue
195 |
196 | for swdata in self.devices.values():
197 | if isinstance(hostname, Device):
198 | swobject = hostname
199 | else:
200 | try:
201 | if ipaddress.ip_address(hostname) == swdata.mgmt_address:
202 | swobject = swdata
203 | break
204 | except ValueError:
205 | # In case hostname is not an IP
206 | pass
207 |
208 | if swdata.hostname == hostname:
209 | swobject = swdata
210 | break
211 |
212 | self.logger.info(
213 | "Demote %s back to Device from Switch", swobject.hostname)
214 | swobject.__class__ = Device
215 | swobject.discovery_status = dt.now()
216 | else:
217 | swobject.discovery_status = dt.now()
218 | self.logger.info(
219 | "Completed discovery of %s", swobject.hostname)
220 | # Check if it has cdp neighbors
221 |
222 | for _, intdata in swobject.interfaces.items():
223 | for nei in intdata.neighbors:
224 | self.logger.debug(
225 | "Evaluating neighbour %s", nei['hostname'])
226 | if nei['hostname'] not in self.devices and nei['ip'] not in self.discovery_status:
227 |
228 | scan = True
229 | if neigh_validator_callback is not None:
230 | if isinstance(nei, Device):
231 | self.logger.debug(
232 | "Passing %s to callback function to check whether to scan", nei.device.hostname)
233 | scan = neigh_validator_callback(
234 | nei.device.hostname)
235 | else:
236 | self.logger.debug(
237 | "Passing %s to callback function to check whether to scan", nei['hostname'])
238 | scan = neigh_validator_callback(
239 | nei['hostname'])
240 |
241 | self.logger.debug(
242 | "Callback function returned %s", scan)
243 |
244 | if scan:
245 | self.logger.info(
246 | "Queueing discover for %s", nei['hostname'])
247 | self.discovery_status[nei['ip']
248 | ] = "Queued"
249 |
250 | switch = Device(
251 | nei['ip'], hostname=nei['hostname'])
252 |
253 | future_switch_data[executor.submit(self.add_device,
254 | switch,
255 | credentials,
256 | napalm_optional_args)] = switch
257 | else:
258 | # Add device to fabric without scanning it
259 | self.discovery_status[nei['ip']
260 | ] = "Skipped"
261 |
262 | if nei['hostname'] not in self.devices:
263 | nei_dev = Device(nei['ip'], hostname=nei['hostname'], facts={
264 | 'platform': nei['platform'], 'hostname': nei['hostname']})
265 | self.devices[nei['hostname']
266 | ] = nei_dev
267 |
268 | remote_int = Interface(
269 | name=nei['remote_int'])
270 | nei_dev.add_interface(remote_int)
271 |
272 | self.logger.info(
273 | "Skipping %s, callback returned False", nei['hostname'])
274 | else:
275 | self.logger.debug(
276 | "Skipping %s, already discovered", nei['hostname'])
277 |
278 | self.logger.info("Discovery complete, crunching data")
279 | self.refresh_global_information()
280 |
281 | def refresh_global_information(self):
282 | """
283 | Update global information such as mac address position
284 | and cdp neighbor adjacency
285 | """
286 | self.logger.debug("Refreshing information")
287 | self._recalculate_macs()
288 | self._find_links()
289 |
290 | def _find_links(self):
291 | """
292 | Join switches by CDP neighborship
293 | """
294 | short_fabric = {k[:40]: v for k, v in self.devices.items()}
295 | hostname_only_fabric = {}
296 |
297 | for k, v in self.devices.items():
298 | if v.facts is not None:
299 | hostname_only_fabric[v.facts['hostname']] = v
300 | else:
301 | hostname_only_fabric[k] = k
302 |
303 | for swdata in self.devices.values():
304 | for intfdata in swdata.interfaces.values():
305 | if hasattr(intfdata, "neighbors"):
306 | for i in intfdata.neighbors:
307 | if isinstance(i, Interface):
308 | continue
309 |
310 | switch = i['hostname']
311 | port = i['remote_int']
312 |
313 | try:
314 | peer_device = self.devices[switch]
315 | except KeyError:
316 | try:
317 | peer_device = short_fabric[switch[:40]]
318 | except KeyError:
319 | try:
320 | peer_device = hostname_only_fabric[switch]
321 | except KeyError:
322 | self.logger.debug("Could not find link between %s %s and %s %s",
323 | intfdata.name, intfdata.device.facts['fqdn'], port, switch)
324 | continue
325 |
326 | try:
327 | neigh_int = peer_device.interfaces[port]
328 | except KeyError:
329 | # missing interface, add it
330 | neigh_int = Interface(
331 | name=port, switch=peer_device)
332 | peer_device.add_interface(neigh_int)
333 |
334 | intfdata.neighbors.remove(i)
335 |
336 | intfdata.add_neighbor(neigh_int)
337 |
338 | self.logger.debug("Found link between %s %s and %s %s", intfdata.name,
339 | intfdata.device.hostname, neigh_int.name, neigh_int.device.hostname)
340 |
341 | def _recalculate_macs(self):
342 | """
343 | Refresh count macs per interface.
344 | Tries to guess where mac addresses are by assigning them to the interface with the lowest total mac count
345 | """
346 | for swdata in self.devices.values():
347 | if isinstance(swdata, Switch):
348 | for intdata in swdata.interfaces.values():
349 | intdata.mac_count = 0
350 |
351 | for data in swdata.mac_table.values():
352 | try:
353 | data['interface'].mac_count += 1
354 | except KeyError:
355 | pass
356 |
357 | for swdata in self.devices.values():
358 | if isinstance(swdata, Switch):
359 | for mac, macdata in swdata.mac_table.items():
360 | try:
361 | if self.mac_table[mac]['interface'].mac_count > macdata['interface'].mac_count:
362 | self.logger.debug("Found better interface %s %s for %s",
363 | macdata['interface'].name, macdata['interface'].device.hostname, str(mac))
364 | self.mac_table[mac] = macdata
365 | except KeyError:
366 | self.mac_table[mac] = macdata
367 |
368 | def find_paths(self, start_sw, end_sw):
369 | """
370 | Return a list of all interfaces from 'start' Switch to 'end' Switch
371 |
372 | :param start_sw: Switch to begin search from
373 | :type start_sw: netwalk.Switch
374 | :param end_sw: List of target switch or switches
375 | :type end_sw: netwalk.Switch
376 | """
377 | def _inside_recursive(start_int, end_sw, path=None):
378 | if path is None:
379 | path = []
380 |
381 | switch = start_int.neighbors[0].device
382 | path = path + [start_int.neighbors[0]]
383 | if switch in end_sw:
384 | return [path]
385 | paths = []
386 | for _, intdata in switch.interfaces.items():
387 | if hasattr(intdata, 'neighbors'):
388 | if len(intdata.neighbors) == 1:
389 | if type(intdata.neighbors[0]) == Interface:
390 | neigh_int = intdata.neighbors[0]
391 | if type(neigh_int) == Interface:
392 | if intdata not in path:
393 | this_path = path + [intdata]
394 | newpaths = _inside_recursive(
395 | intdata, end_sw, this_path)
396 | for newpath in newpaths:
397 | paths.append(newpath)
398 |
399 | return paths
400 |
401 | all_possible_paths = []
402 | for intdata in start_sw.interfaces.values():
403 | if hasattr(intdata, 'neighbors'):
404 | if len(intdata.neighbors) == 1:
405 | if type(intdata.neighbors[0]) == Interface:
406 | assert len(end_sw) > 0
407 | thispath = _inside_recursive(
408 | intdata, end_sw, path=[intdata])
409 | for path in thispath:
410 | all_possible_paths.append(path)
411 |
412 | return all_possible_paths
413 |
--------------------------------------------------------------------------------
/netwalk/interface.py:
--------------------------------------------------------------------------------
1 | """
2 | netwalk
3 | Copyright (C) 2021 NTT Ltd
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU Affero General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU Affero General Public License for more details.
14 |
15 | You should have received a copy of the GNU Affero General Public License
16 | along with this program. If not, see .
17 | """
18 |
19 | import ipaddress
20 | import logging
21 | import re
22 | from datetime import datetime
23 | from typing import Any, ForwardRef, List, Optional
24 |
25 | from netaddr import EUI
26 |
27 | Switch = ForwardRef('Switch')
28 | Interface = ForwardRef('Interface')
29 |
30 |
31 | class Interface():
32 | """
33 | Define an interface
34 | Can be initialised with any of the values or by passing
35 | an array containing each line of the interface configuration.
36 |
37 | Converted to str it outputs the corresponding show running configuration.
38 | All unparsed lines go to "unparsed_lines" and are returned when converted to str
39 | """
40 |
41 | logger: logging.Logger
42 | name: str
43 | description: Optional[str]
44 | #: data from show interface
45 | abort: Optional[str]
46 | address: dict
47 | allowed_vlan: set
48 | #: data from show interface
49 | bandwidth: Optional[str]
50 | #: data from show interface
51 | bia: Optional[str]
52 | bpduguard: bool
53 | channel_group: Optional[int]
54 | channel_protocol: Optional[str]
55 | child_interfaces: List[Interface]
56 | config: List[str]
57 | counters: Optional[dict]
58 | #: data from show interface
59 | crc: Optional[str]
60 | #: data from show interface
61 | delay: Optional[str]
62 | device: Optional[Switch]
63 | #: data from show interface
64 | duplex: Optional[str]
65 | encapsulation: Optional[str]
66 | #: data from show interface
67 | hardware_type: Optional[str]
68 | #: data from show interface
69 | input_errors: Optional[str]
70 | #: data from show interface
71 | input_packets: Optional[str]
72 | #: data from show interface
73 | input_rate: Optional[str]
74 | is_enabled: bool
75 | is_up: bool
76 | #: data from show interface
77 | last_clearing: Optional[datetime]
78 | #: data from show interface
79 | last_in: Optional[datetime]
80 | #: data from show interface
81 | last_out_hang: Optional[datetime]
82 | #: data from show interface
83 | last_out: Optional[datetime]
84 | mac_address: Optional[EUI]
85 | #: Total number of mac addresses behind this interface
86 | mac_count: int = 0
87 | #: data from show interface
88 | media_type: Optional[str]
89 | mode: str
90 | #: data from show interface
91 | mtu: Optional[int]
92 | native_vlan: int
93 | # TODO: can be a list of either dict or Interface
94 | #: List of neighbors connected to the interface. List because CDP might show more than one.
95 | #: If the neighbour is another Switch, it's turned into the other end's Interface object
96 | #: otherwise remains a dict containing all the parsed data.
97 | neighbors: List[Any]
98 | #: data from show interface
99 | output_errors: Optional[str]
100 | #: data from show interface
101 | output_packets: Optional[str]
102 | #: data from show interface
103 | output_rate: Optional[str]
104 | parent_interface: Optional[Interface]
105 | protocol_status: Optional[str]
106 | #: data from show interface
107 | queue_strategy: Optional[str]
108 | routed_port: bool
109 | sort_order: Optional[int]
110 | #: data from show interface
111 | speed: Optional[str]
112 | #: pointer to parent's Switch object
113 | switch: Optional[Switch]
114 | type_edge: bool
115 | unparsed_lines: List[str]
116 | voice_vlan: Optional[int]
117 | vrf: str
118 |
119 | def __init__(self, **kwargs):
120 | from netwalk.device import Switch
121 | self.name: str = kwargs.get('name')
122 | self.description: Optional[str] = kwargs.get('description', "")
123 |
124 | self.abort: Optional[str] = kwargs.get('abort')
125 | self.address: dict = kwargs.get('address', {})
126 | self.allowed_vlan: set = kwargs.get('allowed_vlan')
127 | self.bandwidth: Optional[str] = kwargs.get('bandwidth')
128 | self.bia: Optional[str] = kwargs.get('bia')
129 | self.bpduguard: bool = kwargs.get('bpduguard', False)
130 | self.channel_group: Optional[int] = kwargs.get('channel_group')
131 | self.channel_protocol: Optional[str] = kwargs.get('channel_protocol')
132 | self.child_interfaces: List[Interface] = kwargs.get(
133 | 'child_interfaces', [])
134 | self.config: List[str] = kwargs.get('config')
135 | self.counters: Optional[dict] = kwargs.get('counters')
136 | self.device: Optional[Switch] = kwargs.get('device')
137 | self.crc: Optional[str] = kwargs.get('crc')
138 | self.delay: Optional[str] = kwargs.get('delay')
139 | self.duplex: Optional[str] = kwargs.get('duplex')
140 | self.encapsulation: Optional[str] = kwargs.get('encapsulation')
141 | self.hardware_type: Optional[str] = kwargs.get('hardware_type')
142 | self.input_errors: Optional[str] = kwargs.get('input_errors')
143 | self.input_packets: Optional[str] = kwargs.get('input_packets')
144 | self.input_rate: Optional[str] = kwargs.get('input_rate')
145 | self.is_enabled: bool = kwargs.get('is_enabled', True)
146 | self.is_up: bool = kwargs.get('is_up', True)
147 | self.last_clearing: Optional[datetime] = kwargs.get('last_clear')
148 | self.last_in: Optional[datetime] = kwargs.get('last_in')
149 | self.last_out_hang: Optional[datetime] = kwargs.get('last_out_hang')
150 | self.last_out: Optional[datetime] = kwargs.get('last_out')
151 | self.mac_address: Optional[EUI] = kwargs.get('mac_address')
152 | self.mac_count: int = 0
153 | self.media_type: Optional[str] = kwargs.get('media_type')
154 | self.mode: str = kwargs.get('mode', 'access')
155 | self.mtu: Optional[int] = kwargs.get('mtu')
156 | self.native_vlan: int = kwargs.get('native_vlan', 1)
157 | self.neighbors: List[Any[Interface, dict]
158 | ] = kwargs.get('neighbors', [])
159 | self.output_errors: Optional[str] = kwargs.get('output_errors')
160 | self.output_packets: Optional[str] = kwargs.get('output_packets')
161 | self.output_rate: Optional[str] = kwargs.get('output_rate')
162 | self.parent_interface: Optional[Interface] = kwargs.get(
163 | 'parent_interface')
164 | self.protocol_status: Optional[str] = kwargs.get('protocol_status')
165 | self.queue_strategy: Optional[str] = kwargs.get('queue_strategy')
166 | self.routed_port: bool = kwargs.get('routed_port', False)
167 | self.sort_order: Optional[int] = kwargs.get('sort_order')
168 | self.speed: Optional[str] = kwargs.get('speed')
169 | self.type_edge: bool = kwargs.get('type_edge', False)
170 | self.unparsed_lines: List[str] = kwargs.get('unparsed_lines', [])
171 | self.voice_vlan: Optional[int] = kwargs.get('voice_vlan')
172 | self.vrf: str = kwargs.get('vrf', "default")
173 |
174 | if self.name is None:
175 | self.logger = logging.getLogger(__name__)
176 | else:
177 | self.logger = logging.getLogger(__name__ + self.name)
178 |
179 | if self.config is not None:
180 | self.parse_config()
181 | else:
182 | self.config = []
183 |
184 | if self.name is not None:
185 | self._calculate_sort_order()
186 |
187 | def parse_config(self, second_pass=False):
188 | "Parse configuration from show run"
189 | if isinstance(self.config, str):
190 | self.config = self.config.split("\n")
191 |
192 | if not second_pass:
193 | # Pass values to unparsed_lines as value not reference
194 | self.unparsed_lines = [x.rstrip() for x in self.config[:]]
195 |
196 | # Parse port mode first. Some switches have it first, some last, so check it first thing
197 | for line in self.unparsed_lines:
198 | cleanline = line.strip()
199 | match = re.search(r"switchport mode (.*)$", cleanline)
200 | if match is not None:
201 | self.mode = match.groups()[0].strip()
202 | if self.mode == 'trunk' and self.allowed_vlan is None:
203 | self.allowed_vlan = set([x for x in range(1, 4095)])
204 | self.unparsed_lines.remove(line)
205 | continue
206 |
207 | # Cycle through lines, make second array so we don't modify data we are looping over
208 | for line in [x for x in self.unparsed_lines]:
209 | cleanline = line.strip()
210 |
211 | # L2 data
212 | # Find interface name
213 | match = re.search(
214 | r"^interface ([A-Za-z\-]*(\/*\d*)+\.?\d*)", cleanline)
215 | if match is not None:
216 | if self.name is None:
217 | self.logger = logging.getLogger(
218 | __name__ + match.groups()[0])
219 |
220 | self.name = match.groups()[0]
221 | if "vlan" in self.name.lower():
222 | self.routed_port = True
223 | self.mode = 'access'
224 | self.native_vlan = int(
225 | self.name.lower().replace("vlan", ""))
226 |
227 | self.unparsed_lines.remove(line)
228 | continue
229 |
230 | # Find description
231 | match = re.search(r"description (.*)$", cleanline)
232 | if match is not None:
233 | self.description = match.groups()[0]
234 | self.unparsed_lines.remove(line)
235 | continue
236 |
237 | # Port channel ownership
238 | match = re.search(r"channel\-group (\d+) mode (\w+)", cleanline)
239 | if match is not None:
240 | po_id, mode = match.groups()
241 | if self.device is not None:
242 | parent_po = self.device.interfaces.get(
243 | f'Port-channel{str(po_id)}', None)
244 | if parent_po is not None:
245 | parent_po.add_child_interface(self)
246 | self.unparsed_lines.remove(line)
247 |
248 | self.channel_group = po_id
249 | self.channel_protocol = mode
250 | continue
251 |
252 | # Native vlan
253 | match = re.search(r"switchport access vlan (.*)$", cleanline)
254 | if match is not None and self.mode != 'trunk':
255 | self.native_vlan = int(match.groups()[0])
256 | self.unparsed_lines.remove(line)
257 | continue
258 |
259 | # Voice native vlan
260 | match = re.search(r"switchport voice vlan (.*)$", cleanline)
261 | if match is not None and self.mode == 'access':
262 | self.voice_vlan = int(match.groups()[0])
263 | self.unparsed_lines.remove(line)
264 | continue
265 |
266 | # Trunk native vlan
267 | match = re.search(r"switchport trunk native vlan (.*)$", cleanline)
268 | if match is not None and self.mode == 'trunk':
269 | self.native_vlan = int(match.groups()[0])
270 | self.unparsed_lines.remove(line)
271 | continue
272 |
273 | # Trunk allowed vlan
274 | match = re.search(
275 | r"switchport trunk allowed vlan ([0-9\-\,]*)$", cleanline)
276 | if match is not None:
277 | self.allowed_vlan = self._allowed_vlan_to_list(
278 | match.groups()[0])
279 | self.unparsed_lines.remove(line)
280 | continue
281 |
282 | # Trunk allowed vlan add
283 | match = re.search(
284 | r"switchport trunk allowed vlan add ([0-9\-\,]*)$", cleanline)
285 | if match is not None:
286 | new_vlans = self._allowed_vlan_to_list(match.groups()[0])
287 | self.allowed_vlan.update(list(new_vlans))
288 | self.unparsed_lines.remove(line)
289 | continue
290 |
291 | # Tagged routed interface
292 | match = re.search(
293 | r"encapsulation dot1q?Q? (\d*)( native)?$", cleanline)
294 | if match is not None:
295 | self.mode = "access"
296 | self.native_vlan = int(match.groups()[0])
297 | self.unparsed_lines.remove(line)
298 | continue
299 |
300 | # Portfast
301 | match = re.search(
302 | r"spanning-tree portfast", cleanline)
303 | if match is not None:
304 | if "trunk" in cleanline and self.mode == "trunk":
305 | self.type_edge = True
306 | elif "trunk" not in cleanline and self.mode == "access":
307 | self.type_edge = True
308 |
309 | self.unparsed_lines.remove(line)
310 | continue
311 |
312 | match = re.search(
313 | r"spanning-tree bpduguard", cleanline)
314 | if match is not None:
315 | self.bpduguard = True
316 | self.unparsed_lines.remove(line)
317 | continue
318 |
319 | if "no shutdown" in line:
320 | self.logger.debug("Set shutdown = False")
321 | self.is_enabled = True
322 | self.unparsed_lines.remove(line)
323 | continue
324 | elif "shutdown" in line:
325 | self.logger.debug("Set shutdown = True")
326 | self.is_enabled = False
327 | self.unparsed_lines.remove(line)
328 | continue
329 |
330 | # Legacy syntax, ignore
331 | if "switchport trunk encapsulation" in line:
332 | self.unparsed_lines.remove(line)
333 | continue
334 |
335 | # L3 parsing
336 | # Parse VRF
337 | match = re.search(
338 | r'vrf forwarding (.*)', cleanline)
339 | if match is not None:
340 | self.vrf = match.groups()[0]
341 | self.unparsed_lines.remove(line)
342 | continue
343 |
344 | # Parse 'normal' ipv4 address
345 | match = re.search(
346 | r'ip address (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s?(secondary)?', cleanline)
347 | if match is not None:
348 | address, netmask, secondary = match.groups()
349 | addrobj = ipaddress.ip_interface(f"{address}/{netmask}")
350 |
351 | addr_type = 'primary' if secondary is None else 'secondary'
352 |
353 | try:
354 | assert 'ipv4' in self.address
355 | except AssertionError:
356 | self.address['ipv4'] = {}
357 |
358 | self.address['ipv4'][addrobj] = {'type': addr_type}
359 | self.routed_port = True
360 | self.unparsed_lines.remove(line)
361 | continue
362 |
363 | # Parse HSRP addresses
364 | match = re.search(
365 | r"standby (\d{1,3})?\s?(ip|priority|preempt|version)\s?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|\d*)?\s?(secondary)?", cleanline)
366 | if match is not None:
367 | grpid, command, argument, secondary = match.groups()
368 | if grpid is None:
369 | grpid = 0
370 | else:
371 | grpid = int(grpid)
372 |
373 | try:
374 | assert 'hsrp' in self.address
375 | except AssertionError:
376 | self.address['hsrp'] = {'version': 1, 'groups': {}}
377 |
378 | if command == 'version':
379 | self.address['hsrp']['version'] = int(argument)
380 | self.unparsed_lines.remove(line)
381 | continue
382 |
383 | try:
384 | assert grpid in self.address['hsrp']['groups']
385 | except AssertionError:
386 | self.address['hsrp']['groups'][grpid] = {
387 | 'priority': 100, 'preempt': False, 'secondary': []}
388 |
389 | if command == 'ip':
390 | if secondary is not None:
391 | self.address['hsrp']['groups'][grpid]['secondary'].append(
392 | ipaddress.ip_address(argument))
393 | else:
394 | self.address['hsrp']['groups'][grpid]['address'] = ipaddress.ip_address(
395 | argument)
396 | elif command == 'priority':
397 | self.address['hsrp']['groups'][grpid]['priority'] = int(
398 | argument)
399 | elif command == 'preempt':
400 | self.address['hsrp']['groups'][grpid]['preempt'] = True
401 |
402 | self.unparsed_lines.remove(line)
403 | continue
404 |
405 | if cleanline == '' or cleanline == '!':
406 | self.unparsed_lines.remove(line)
407 |
408 | def add_child_interface(self, child_interface) -> None:
409 | """Method to add interface to child interfaces and assign it a parent"""
410 | self.child_interfaces.append(child_interface)
411 | child_interface.parent_interface = self
412 |
413 | def add_neighbor(self, neigh_int: Interface) -> None:
414 | "Method to add bidirectional neighborship to an interface"
415 | # Add bidirectional link
416 | if neigh_int not in self.neighbors:
417 | self.neighbors.append(neigh_int)
418 | if self not in neigh_int.neighbors:
419 | neigh_int.neighbors.append(self)
420 |
421 | def _calculate_sort_order(self) -> None:
422 | """Generate unique sorting number from port id to sort interfaces meaningfully"""
423 | if 'Port-channel' in self.name:
424 | id = self.name.replace('Port-channel', '')
425 | self.sort_order = int(id) + 1000000
426 |
427 | elif 'Ethernet' in self.name:
428 | try:
429 | portid = self.name.split('Ethernet')[1]
430 | except IndexError:
431 | self.sort_order = 0
432 |
433 | sortid = ""
434 | port_number = portid.split('/')
435 |
436 | if "." in port_number[-1]:
437 | last_port, subint = port_number[-1].split(".")
438 | else:
439 | last_port = port_number[-1]
440 | subint = 0
441 | for i in port_number[0:-1]:
442 | sortid += str(i).zfill(3)
443 |
444 | sortid += str(last_port).zfill(3)
445 | sortid += str(subint).zfill(4)
446 |
447 | self.sort_order = int(sortid.replace(" ", ""))
448 |
449 | def _allowed_vlan_to_list(self, vlanlist: str) -> set:
450 | """
451 | Expands vlan ranges
452 |
453 | :param vlanlist: String of vlans from config, i.e. 1,2,3-5
454 | :type vlanlist: str
455 |
456 | :return: Set of vlans
457 | :rtype: set
458 | """
459 |
460 | split = vlanlist.split(",")
461 | out = set()
462 | for vlan in split:
463 | if "-" in vlan:
464 | begin, end = vlan.split("-")
465 | out.update(range(int(begin), int(end)+1))
466 | else:
467 | out.add(int(vlan))
468 |
469 | return out
470 |
471 | def generate_config(self, full=False) -> str:
472 | """Generate show run from self data"""
473 |
474 | if self.name is None:
475 | raise KeyError("Must define at least a name")
476 |
477 | fullconfig = f"interface {self.name}\n"
478 |
479 | if self.description != "":
480 | fullconfig += f" description {self.description}\n"
481 | elif full:
482 | fullconfig += " no description\n"
483 |
484 | if isinstance(self.parent_interface, Interface):
485 | if "Port-channel" in self.parent_interface.name:
486 | fullconfig += f" channel-group {self.channel_group} mode {self.channel_protocol}\n"
487 |
488 | if not self.routed_port:
489 | fullconfig += f" switchport mode {self.mode}\n"
490 |
491 | if self.mode == "access":
492 | if full:
493 | fullconfig += " no switchport trunk native vlan\n no switchport trunk allowed vlan\n"
494 |
495 | fullconfig += f" switchport access vlan {self.native_vlan}\n"
496 |
497 | elif self.mode == "trunk":
498 | if full:
499 | fullconfig += " no switchport access vlan\n"
500 |
501 | fullconfig += f" switchport trunk native vlan {self.native_vlan}\n"
502 | if self.allowed_vlan is None:
503 | fullconfig = fullconfig + " switchport trunk allowed vlan all\n"
504 | elif len(self.allowed_vlan) != 4094:
505 | sorted_allowed_vlan = list(self.allowed_vlan)
506 | sorted_allowed_vlan.sort()
507 | vlan_str = ",".join(map(str, sorted_allowed_vlan))
508 | fullconfig += f" switchport trunk allowed vlan {vlan_str}\n"
509 | else:
510 | fullconfig += " switchport trunk allowed vlan all\n"
511 | else:
512 | self.logger.warning("Port %s mode %s", self.name, self.mode)
513 |
514 | if self.mode == "access" and self.voice_vlan is not None:
515 | fullconfig += f" switchport voice vlan {self.voice_vlan}\n"
516 | elif full:
517 | fullconfig += " no switchport voice vlan\n"
518 |
519 | if self.type_edge:
520 | fullconfig += " spanning-tree portfast"
521 |
522 | if self.mode == "trunk":
523 | fullconfig += " trunk\n"
524 | else:
525 | fullconfig += "\n"
526 | elif full:
527 | fullconfig += " no spanning-tree portfast\n"
528 |
529 | if self.bpduguard:
530 | fullconfig = fullconfig + " spanning-tree bpduguard enable\n"
531 | elif full:
532 | fullconfig += " no spanning-tree bpduguard\n"
533 |
534 | else:
535 | if self.vrf != 'default':
536 | fullconfig += " vrf forwarding " + self.vrf + "\n"
537 | elif full:
538 | fullconfig += " no vrf forwarding\n"
539 |
540 | if 'ipv4' in self.address:
541 | for k, v in self.address['ipv4'].items():
542 | fullconfig += f" ip address {k.ip} {k.netmask}"
543 | if v['type'] == 'secondary':
544 | fullconfig += " secondary\n"
545 | elif v['type'] == 'primary':
546 | fullconfig += "\n"
547 | elif full:
548 | fullconfig += " no ip address\n"
549 |
550 | if 'hsrp' in self.address:
551 | if self.address['hsrp']['version'] != 1:
552 | fullconfig += " standby version " + \
553 | str(self.address['hsrp']['version']) + "\n"
554 | for k, v in self.address['hsrp']['groups'].items():
555 | line_begin = f" standby {k} " if k != 0 else " standby "
556 | fullconfig = fullconfig + line_begin + \
557 | "ip " + str(v['address']) + "\n"
558 | for secaddr in v['secondary']:
559 | fullconfig = fullconfig + line_begin + \
560 | "ip " + str(secaddr) + " secondary\n"
561 | if v['priority'] != 100:
562 | fullconfig = fullconfig + line_begin + \
563 | "priority " + str(v['priority']) + "\n"
564 | if v['preempt']:
565 | fullconfig = fullconfig + line_begin + "preempt\n"
566 |
567 | for line in self.unparsed_lines:
568 | fullconfig = fullconfig + line + "\n"
569 |
570 | if self.is_enabled:
571 | fullconfig = fullconfig + " no shutdown\n"
572 | else:
573 | fullconfig = fullconfig + " shutdown\n"
574 |
575 | fullconfig = fullconfig + "!\n"
576 | return fullconfig
577 |
578 | def __str__(self) -> str:
579 | return self.generate_config()
580 |
--------------------------------------------------------------------------------
/netwalk/libs.py:
--------------------------------------------------------------------------------
1 | "Miscellaneous functions that can be useful across objects"
2 |
3 |
4 | def interface_name_expander(name):
5 | mapping = {'Fa': 'FastEthernet',
6 | 'Gi': 'GigabitEthernet',
7 | 'Te': 'TenGigabitEthernet',
8 | 'Po': 'Port-Channel',
9 | 'Twe': 'TwentyFiveGigE'}
10 |
11 | for k, v in mapping.items():
12 | if name.startswith(k):
13 | return name.replace(k, v)
14 |
15 | return name
16 |
--------------------------------------------------------------------------------
/netwalk/textfsm_templates/show_cdp_neigh_detail.textfsm:
--------------------------------------------------------------------------------
1 | Value Filldown local_host (\S+)
2 | Value Required dest_host (\S+)
3 | Value mgmt_ip (.*)
4 | Value platform (.*)
5 | Value remote_port (.*)
6 | Value local_port (.*)
7 | Value version (.*)
8 |
9 | Start
10 | ^${local_host}[>#].*
11 | ^Device ID: ${dest_host}
12 | ^Entry address\(es\): -> ParseIP
13 | ^Platform: ${platform},
14 | ^Interface: ${local_port}, Port ID \(outgoing port\): ${remote_port}
15 | ^Version : -> GetVersion
16 |
17 | ParseIP
18 | ^.*IP address: ${mgmt_ip} -> Start
19 | ^Platform: -> Start
20 |
21 | GetVersion
22 | ^${version} -> Record Start
--------------------------------------------------------------------------------
/netwalk/textfsm_templates/show_interface.textfsm:
--------------------------------------------------------------------------------
1 | Value Required name (\S+)
2 | Value is_enabled (.+?)
3 | Value is_up (.+?)
4 | Value hardware_type ([\w ]+)
5 | Value mac_address ([a-fA-F0-9]{4}\.[a-fA-F0-9]{4}\.[a-fA-F0-9]{4})
6 | Value bia ([a-fA-F0-9]{4}\.[a-fA-F0-9]{4}\.[a-fA-F0-9]{4})
7 | Value description (.+?)
8 | Value mtu (\d+)
9 | Value duplex (([Ff]ull|[Aa]uto|[Hh]alf|[Aa]-).*?)
10 | Value speed (.*?)
11 | Value media_type (\S+(\s+\S+)?)
12 | Value bandwidth (\d+\s+\w+)
13 | Value delay (\d+\s+\S+)
14 | Value encapsulation (.+?)
15 | Value last_in (.+?)
16 | Value last_out (.+?)
17 | Value last_out_hang (.+?)
18 | Value last_clearing (.*)
19 | Value queue_strategy (.+)
20 | Value input_rate (\d+)
21 | Value output_rate (\d+)
22 | Value input_packets (\d+)
23 | Value output_packets (\d+)
24 | Value input_errors (\d+)
25 | Value crc (\d+)
26 | Value abort (\d+)
27 | Value output_errors (\d+)
28 |
29 | Start
30 | ^\S+\s+is\s+.+?,\s+line\s+protocol.*$$ -> Continue.Record
31 | ^${name}\s+is\s+${is_enabled},\s+line\s+protocol\s+is\s+${is_up}\s*$$
32 | ^\s+Hardware\s+is\s+${hardware_type} -> Continue
33 | ^.+address\s+is\s+${mac_address}\s+\(bia\s+${bia}\)\s*$$
34 | ^\s+Description:\s+${description}\s*$$
35 | ^\s+Internet\s+address\s+is.+$$
36 | ^\s+MTU\s+${mtu}.*BW\s+${bandwidth}.*DLY\s+${delay},\s*$$
37 | ^\s+Encapsulation\s+${encapsulation},.+$$
38 | ^\s+Last\s+input\s+${last_in},\s+output\s+${last_out},\s+output\s+hang\s+${last_out_hang}\s*$$
39 | ^\s+Last\s+clearing\s+of\s+"show interface"\s+counters\s+${last_clearing}$$
40 | ^\s+Queueing\s+strategy:\s+${queue_strategy}\s*$$
41 | ^\s+${duplex},\s+${speed},.+media\stype\sis\s${media_type}$$
42 | ^.*input\s+rate\s+${input_rate}.+$$
43 | ^.*output\s+rate\s+${output_rate}.+$$
44 | ^\s+${input_packets}\s+packets\s+input,\s+\d+\s+bytes,\s+\d+\s+no\s+buffer\s*$$
45 | ^\s+${input_errors}\s+input\s+errors,\s+${crc}\s+CRC,\s+\d+\s+frame,\s+\d+\s+overrun,\s+\d+\s+ignored\s*$$
46 | ^\s+${input_errors}\s+input\s+errors,\s+${crc}\s+CRC,\s+\d+\s+frame,\s+\d+\s+overrun,\s+\d+\s+ignored,\s+${abort}\s+abort\s*$$
47 | ^\s+${output_packets}\s+packets\s+output,\s+\d+\s+bytes,\s+\d+\s+underruns\s*$$
48 | ^\s+${output_errors}\s+output\s+errors,\s+\d+\s+collisions,\s+\d+\s+interface\s+resets\s*$$
49 | # Capture time-stamp if vty line has command time-stamping turned on
50 | ^Load\s+for\s+
51 | ^Time\s+source\s+is
--------------------------------------------------------------------------------
/netwalk/textfsm_templates/show_inventory.textfsm:
--------------------------------------------------------------------------------
1 | Value name (.*)
2 | Value descr (.*)
3 | Value pid (([\S+]+|.*))
4 | Value vid (.*)
5 | Value sn ([\w+\d+]+)
6 |
7 | Start
8 | ^NAME:\s+"${name}",\s+DESCR:\s+"${descr}"
9 | ^PID:\s+${pid}.*,.*VID:\s+${vid},.*SN:\s+${sn} -> Record
10 | ^PID:\s+,.*VID:\s+${vid},.*SN: -> Record
11 | ^PID:\s+${pid}.*,.*vid:\s+${vid},.*SN: -> Record
12 | ^PID:\s+,.*VID:\s+${vid},.*SN:\s+${sn} -> Record
13 | ^PID:\s+${pid}.*,.*VID:\s+${vid}.*
14 | ^PID:\s+,.*VID:\s+${vid}.*
15 | ^.*SN:\s+${sn} -> Record
16 | ^.*SN: -> Record
17 | # Capture time-stamp if vty line has command time-stamping turned on
18 | ^Load\s+for\s+
19 | ^Time\s+source\s+is
--------------------------------------------------------------------------------
/netwalk/textfsm_templates/show_lldp_neigh_detail.textfsm:
--------------------------------------------------------------------------------
1 | Value Filldown local_host (\S+)
2 | Value local_port (\S+)
3 | Value chassis_id (\S+)
4 | Value remote_port_id (.*)
5 | Value remote_port (.*)
6 | Value neighbor (.+?)
7 | Value system_description (.*)
8 | Value capabilities (.*)
9 | Value mgmt_ip (\S+)
10 | Value vlan (\d+)
11 | Value serial (\S+)
12 |
13 | Start
14 | ^.*not advertised
15 | ^.*Invalid input detected -> EOF
16 | ^.*LLDP is not enabled -> EOF
17 | ^Local\s+Intf:\s+${local_port}\s*$$
18 | ^Chassis\s+id:\s+${chassis_id}\s*$$
19 | ^Port\s+id:\s+${remote_port_id}\s*$$
20 | ^Port\s+Description:\s+${remote_port}\s*$$
21 | ^System\s+Name(\s+-\s+not\s+advertised)\s*$$
22 | ^System\s+Name:?\s*$$
23 | ^System\s+Name(:\s+${neighbor})\s*$$
24 | ^System\s+Description -> GetDescription
25 | ^Time
26 | ^System\s+Capabilities
27 | ^Enabled\s+Capabilities:\s+${capabilities}\s*$$
28 | ^Management\s+Addresses
29 | ^\s+OID
30 | ^\s+[\d+\.]{8,}
31 | ^.*IP:\s+${mgmt_ip}
32 | ^Auto\s+Negotiation
33 | ^Physical\s+media
34 | # Removed \(\s+\) from the template - The line 'Other/unknown' would not be captured
35 | # Now looks for any text beginning with any space
36 | ^\s+.+\s*$$
37 | ^Media\s+Attachment
38 | ^\s+Inventory
39 | ^\s+Capabilities
40 | ^\s+Device\s+type
41 | ^\s+Network\s+Policies
42 | ^\s+Power\s+requirements
43 | ^\s+Location
44 | ^Time\s+remaining
45 | ^Vlan\s+ID:\s+(?:${vlan}|-\s+not\s+advertised)\s*$$
46 | ^\s+\(\S+\)
47 | ^(?:PoE|\s+Power)
48 | ^\s*-+\s*$$ -> Record
49 | ^MED -> Med
50 | ^\s*\^\s*
51 | ^\s*Total\s+entries\s+displayed -> Record End
52 | ^\s*$$
53 | # Capture time-stamp if vty line has command time-stamping turned on
54 | ^Load\s+for\s+
55 | ^Time\s+source\s+is
56 |
57 | GetDescription
58 | ^${system_description} -> IgnoreDescription
59 |
60 | IgnoreDescription
61 | ^Time\s+remaining -> Start
62 | ^\S*
63 | ^\s*$$
64 | ^.* -> Error
65 |
66 | Med
67 | ^\s+Serial\s+number:\s+${serial}
68 | ^\s+\S+
69 | ^\s*$$
70 | ^\s*Total\s+entries\s+displayed -> Record End
71 | ^\s*-+\s*$$ -> Continue.Record
72 | ^\s*-+\s*$$ -> Start
73 | ^.* -> Error
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | ciscoconfparse==1.6.53
2 | napalm==4.0.0
3 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | # -*- coding: UTF-8 -*-
2 | import setuptools
3 | with open("README.md", "r", encoding="utf-8") as fh:
4 | long_description = fh.read()
5 |
6 | setuptools.setup(
7 | name = "netwalk",
8 | version = "1.6.1",
9 | author = "Federico Tabbò (Europe)",
10 | author_email = "federico.tabbo@global.ntt",
11 | description = "Network discovery and analysis tool",
12 | long_description = long_description,
13 | long_description_content_type = "text/markdown",
14 | url = "https://github.com/icovada/netwalk",
15 | project_urls = {
16 | "Bug Tracker": "https://github.com/icovada/netwalk/issues"
17 | },
18 | classifiers = [
19 | "Programming Language :: Python :: 3",
20 | "Operating System :: OS Independent"
21 | ],
22 | packages = setuptools.find_packages(),
23 | python_requires = ">=3.10",
24 | install_requires=[
25 | "ciscoconfparse==1.6.50",
26 | "napalm==4.0.0"
27 | ],
28 | include_package_data=True
29 | )
30 |
--------------------------------------------------------------------------------
/tests/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/icovada/netwalk/bb58faaa6eb1234ffe1a3a38a9a1e501fe1a360a/tests/__init__.py
--------------------------------------------------------------------------------
/tests/test_fabric.py:
--------------------------------------------------------------------------------
1 | """
2 | netwalk
3 | Copyright (C) 2021 NTT Ltd
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU Affero General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU Affero General Public License for more details.
14 |
15 | You should have received a copy of the GNU Affero General Public License
16 | along with this program. If not, see .
17 | """
18 |
19 | import unittest
20 | from netwalk import Fabric, Switch, Interface
21 |
22 |
23 | class TestFabricBase(unittest.TestCase):
24 | def test_pathfinding_one_target(self):
25 | """
26 | A --- B
27 | | |
28 | C --- D
29 | Find paths from C to A
30 | """
31 |
32 | f = Fabric()
33 | a = Switch(mgmt_address='1.1.1.1', hostname='A', fabric=f)
34 | b = Switch(mgmt_address='2.2.2.2', hostname='B', fabric=f)
35 | c = Switch(mgmt_address='3.3.3.3', hostname='C', fabric=f)
36 | d = Switch(mgmt_address='4.4.4.4', hostname='D', fabric=f)
37 |
38 | f.devices = {'A': a,
39 | 'B': b,
40 | 'C': c,
41 | 'D': d}
42 |
43 | inta0 = Interface(name='GigabitEthernet0/0')
44 | inta1 = Interface(name='GigabitEthernet0/1')
45 |
46 | intb0 = Interface(name='GigabitEthernet0/0')
47 | intb1 = Interface(name='GigabitEthernet0/1')
48 |
49 | intc0 = Interface(name='GigabitEthernet0/0')
50 | intc1 = Interface(name='GigabitEthernet0/1')
51 |
52 | intd0 = Interface(name='GigabitEthernet0/0')
53 | intd1 = Interface(name='GigabitEthernet0/1')
54 |
55 | a.add_interface(inta0)
56 | a.add_interface(inta1)
57 |
58 | b.add_interface(intb0)
59 | b.add_interface(intb1)
60 |
61 | c.add_interface(intc0)
62 | c.add_interface(intc1)
63 |
64 | d.add_interface(intd0)
65 | d.add_interface(intd1)
66 |
67 | inta0.add_neighbor(intb0)
68 | inta1.add_neighbor(intc1)
69 |
70 | intb0.add_neighbor(inta0)
71 | intb1.add_neighbor(intd1)
72 |
73 | intc0.add_neighbor(intd0)
74 | intc1.add_neighbor(inta1)
75 |
76 | intd0.add_neighbor(intc0)
77 | intd1.add_neighbor(intb1)
78 |
79 | paths = f.find_paths(c, [a])
80 | assert c.interfaces['GigabitEthernet0/0'] in paths[0]
81 | assert d.interfaces['GigabitEthernet0/1'] in paths[0]
82 | assert d.interfaces['GigabitEthernet0/0'] in paths[0]
83 | assert b.interfaces['GigabitEthernet0/0'] in paths[0]
84 | assert b.interfaces['GigabitEthernet0/1'] in paths[0]
85 | assert a.interfaces['GigabitEthernet0/0'] in paths[0]
86 |
87 | assert c.interfaces['GigabitEthernet0/1'] in paths[1]
88 | assert a.interfaces['GigabitEthernet0/1'] in paths[1]
89 |
90 | def test_pathfinding_two_targets(self):
91 | """
92 | A --- B
93 | | |
94 | C --- D
95 | Find paths from C to A or B
96 | """
97 |
98 | f = Fabric()
99 | a = Switch(mgmt_address='1.1.1.1', hostname='A', fabric=f)
100 | b = Switch(mgmt_address='2.2.2.2', hostname='B', fabric=f)
101 | c = Switch(mgmt_address='3.3.3.3', hostname='C', fabric=f)
102 | d = Switch(mgmt_address='4.4.4.4', hostname='D', fabric=f)
103 |
104 | f.devices = {'A': a,
105 | 'B': b,
106 | 'C': c,
107 | 'D': d}
108 |
109 | inta0 = Interface(name='GigabitEthernet0/0')
110 | inta1 = Interface(name='GigabitEthernet0/1')
111 |
112 | intb0 = Interface(name='GigabitEthernet0/0')
113 | intb1 = Interface(name='GigabitEthernet0/1')
114 |
115 | intc0 = Interface(name='GigabitEthernet0/0')
116 | intc1 = Interface(name='GigabitEthernet0/1')
117 |
118 | intd0 = Interface(name='GigabitEthernet0/0')
119 | intd1 = Interface(name='GigabitEthernet0/1')
120 |
121 | a.add_interface(inta0)
122 | a.add_interface(inta1)
123 |
124 | b.add_interface(intb0)
125 | b.add_interface(intb1)
126 |
127 | c.add_interface(intc0)
128 | c.add_interface(intc1)
129 |
130 | d.add_interface(intd0)
131 | d.add_interface(intd1)
132 |
133 | inta0.add_neighbor(intb0)
134 | inta1.add_neighbor(intc1)
135 |
136 | intb0.add_neighbor(inta0)
137 | intb1.add_neighbor(intd1)
138 |
139 | intc0.add_neighbor(intd0)
140 | intc1.add_neighbor(inta1)
141 |
142 | intd0.add_neighbor(intc0)
143 | intd1.add_neighbor(intb1)
144 |
145 | paths = f.find_paths(c, [a, b])
146 | assert c.interfaces['GigabitEthernet0/0'] in paths[0]
147 | assert d.interfaces['GigabitEthernet0/1'] in paths[0]
148 | assert d.interfaces['GigabitEthernet0/0'] in paths[0]
149 | assert b.interfaces['GigabitEthernet0/1'] in paths[0]
150 |
151 | assert not b.interfaces['GigabitEthernet0/0'] in paths[0]
152 | assert not a.interfaces['GigabitEthernet0/0'] in paths[0]
153 |
154 | assert c.interfaces['GigabitEthernet0/1'] in paths[1]
155 | assert a.interfaces['GigabitEthernet0/1'] in paths[1]
156 |
157 | def test_pathfinding_two_targets_dead_end(self):
158 | """
159 | A --- B
160 | | |
161 | C --- D - E
162 | Find paths from C to A or B.
163 | Check E not in path
164 | """
165 |
166 | f = Fabric()
167 | a = Switch(mgmt_address='1.1.1.1', hostname='A', fabric=f)
168 | b = Switch(mgmt_address='2.2.2.2', hostname='B', fabric=f)
169 | c = Switch(mgmt_address='3.3.3.3', hostname='C', fabric=f)
170 | d = Switch(mgmt_address='4.4.4.4', hostname='D', fabric=f)
171 | e = Switch(mgmt_address='5.5.5.5', hostname='E', fabric=f)
172 |
173 | f.devices = {'A': a,
174 | 'B': b,
175 | 'C': c,
176 | 'D': d,
177 | 'E': e}
178 |
179 | inta0 = Interface(name='GigabitEthernet0/0')
180 | inta1 = Interface(name='GigabitEthernet0/1')
181 |
182 | intb0 = Interface(name='GigabitEthernet0/0')
183 | intb1 = Interface(name='GigabitEthernet0/1')
184 |
185 | intc0 = Interface(name='GigabitEthernet0/0')
186 | intc1 = Interface(name='GigabitEthernet0/1')
187 |
188 | intd0 = Interface(name='GigabitEthernet0/0')
189 | intd1 = Interface(name='GigabitEthernet0/1')
190 | intd2 = Interface(name='GigabitEthernet0/2')
191 |
192 | inte2 = Interface(name='GigabitEthernet0/2')
193 |
194 | a.add_interface(inta0)
195 | a.add_interface(inta1)
196 |
197 | b.add_interface(intb0)
198 | b.add_interface(intb1)
199 |
200 | c.add_interface(intc0)
201 | c.add_interface(intc1)
202 |
203 | d.add_interface(intd0)
204 | d.add_interface(intd1)
205 | d.add_interface(intd2)
206 |
207 | e.add_interface(inte2)
208 |
209 | inta0.add_neighbor(intb0)
210 | inta1.add_neighbor(intc1)
211 |
212 | intb0.add_neighbor(inta0)
213 | intb1.add_neighbor(intd1)
214 |
215 | intc0.add_neighbor(intd0)
216 | intc1.add_neighbor(inta1)
217 |
218 | intd0.add_neighbor(intc0)
219 | intd1.add_neighbor(intb1)
220 | intd2.add_neighbor(inte2)
221 |
222 | inte2.add_neighbor(intd2)
223 |
224 | paths = f.find_paths(c, [a, b])
225 | assert e.interfaces['GigabitEthernet0/2'] not in paths[0]
226 |
227 | def test_mac_table(self):
228 | from netaddr import EUI
229 | """
230 | A G0/0 --- G0/0 B
231 | G0/1 G0/1
232 | | |
233 | G0/1 G0/1
234 | C G0/0 --- G0/0 D G0/2 - - PC
235 | Check PC mac is on D-Gi0/2
236 | """
237 |
238 | f = Fabric()
239 | a = Switch(mgmt_address='1.1.1.1', facts={
240 | 'hostname': 'A', 'fqdn': 'A.not set'})
241 | b = Switch(mgmt_address='2.2.2.2', facts={
242 | 'hostname': 'B', 'fqdn': 'B.not set'})
243 | c = Switch(mgmt_address='3.3.3.3', facts={
244 | 'hostname': 'C', 'fqdn': 'C.not set'})
245 | d = Switch(mgmt_address='4.4.4.4', facts={
246 | 'hostname': 'D', 'fqdn': 'D.not set'})
247 |
248 | f.devices = {'A': a,
249 | 'B': b,
250 | 'C': c,
251 | 'D': d}
252 |
253 | a00 = Interface(name='GigabitEthernet0/0',
254 | neighbors=[{'hostname': 'B',
255 | 'remote_int': 'GigabitEthernet0/0'}],
256 | device=a)
257 | a01 = Interface(name='GigabitEthernet0/1',
258 | neighbors=[{'hostname': 'C',
259 | 'remote_int': 'GigabitEthernet0/1'}],
260 | device=a)
261 | b00 = Interface(name='GigabitEthernet0/0',
262 | neighbors=[{'hostname': 'A',
263 | 'remote_int': 'GigabitEthernet0/0'}],
264 | device=b)
265 | b01 = Interface(name='GigabitEthernet0/1',
266 | neighbors=[{'hostname': 'D',
267 | 'remote_int': 'GigabitEthernet0/1'}],
268 | device=b)
269 | c00 = Interface(name='GigabitEthernet0/0',
270 | neighbors=[{'hostname': 'D',
271 | 'remote_int': 'GigabitEthernet0/0'}],
272 | device=c)
273 | c01 = Interface(name='GigabitEthernet0/1',
274 | neighbors=[{'hostname': 'A',
275 | 'remote_int': 'GigabitEthernet0/1'}],
276 | device=c)
277 | c02 = Interface(name='GigabitEthernet0/2',
278 | device=c)
279 | d00 = Interface(name='GigabitEthernet0/0',
280 | neighbors=[{'hostname': 'C',
281 | 'remote_int': 'GigabitEthernet0/0'}],
282 | device=d)
283 | d01 = Interface(name='GigabitEthernet0/1',
284 | neighbors=[{'hostname': 'B',
285 | 'remote_int': 'GigabitEthernet0/1'}],
286 | device=d)
287 |
288 | a.interfaces = {'GigabitEthernet0/0': a00,
289 | 'GigabitEthernet0/1': a01}
290 |
291 | b.interfaces = {'GigabitEthernet0/0': b00,
292 | 'GigabitEthernet0/1': b01}
293 |
294 | c.interfaces = {'GigabitEthernet0/0': c00,
295 | 'GigabitEthernet0/1': c01,
296 | 'GigabitEthernet0/2': c02}
297 |
298 | d.interfaces = {'GigabitEthernet0/0': d00,
299 | 'GigabitEthernet0/1': d01}
300 |
301 | amac = EUI("aa:aa:aa:aa:aa:aa")
302 | bmac = EUI("bb:bb:bb:bb:bb:bb")
303 | cmac = EUI("cc:cc:cc:cc:cc:cc")
304 | dmac = EUI("dd:dd:dd:dd:dd:dd")
305 | pcmac = EUI("01:01:01:01:01:01")
306 |
307 | a.mac_table = {amac: {'interface': a.interfaces['GigabitEthernet0/0']},
308 | cmac: {'interface': b.interfaces['GigabitEthernet0/0']},
309 | pcmac: {'interface': b.interfaces['GigabitEthernet0/0']},
310 | dmac: {'interface': b.interfaces['GigabitEthernet0/1']}}
311 |
312 | b.mac_table = {amac: {'interface': b.interfaces['GigabitEthernet0/0']},
313 | cmac: {'interface': b.interfaces['GigabitEthernet0/1']},
314 | pcmac: {'interface': b.interfaces['GigabitEthernet0/1']},
315 | dmac: {'interface': b.interfaces['GigabitEthernet0/0']}}
316 |
317 | c.mac_table = {amac: {'interface': c.interfaces['GigabitEthernet0/1']},
318 | bmac: {'interface': c.interfaces['GigabitEthernet0/1']},
319 | pcmac: {'interface': c.interfaces['GigabitEthernet0/2']},
320 | dmac: {'interface': c.interfaces['GigabitEthernet0/1']}}
321 |
322 | d.mac_table = {amac: {'interface': d.interfaces['GigabitEthernet0/1']},
323 | bmac: {'interface': d.interfaces['GigabitEthernet0/1']},
324 | pcmac: {'interface': d.interfaces['GigabitEthernet0/1']},
325 | cmac: {'interface': d.interfaces['GigabitEthernet0/1']}}
326 |
327 | f.refresh_global_information()
328 |
329 | assert f.mac_table[pcmac] == {
330 | 'interface': c.interfaces['GigabitEthernet0/2']}
331 | assert c.interfaces['GigabitEthernet0/2'].mac_count == 1
332 |
333 |
334 | if __name__ == '__main__':
335 | unittest.main()
336 |
--------------------------------------------------------------------------------
/tests/test_interface.py:
--------------------------------------------------------------------------------
1 | """
2 | netwalk
3 | Copyright (C) 2021 NTT Ltd
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU Affero General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU Affero General Public License for more details.
14 |
15 | You should have received a copy of the GNU Affero General Public License
16 | along with this program. If not, see .
17 | """
18 |
19 | import unittest
20 | import ipaddress
21 | import netwalk
22 | from netwalk.interface import Interface
23 |
24 |
25 | class BaseInterfaceTester(unittest.TestCase):
26 | def test_empty_config(self):
27 | config = ("interface GigabitEthernet1/0/1\n")
28 |
29 | interface = netwalk.Interface(config=config)
30 |
31 | assert interface.name == "GigabitEthernet1/0/1"
32 | assert interface.mode == "access"
33 | assert interface.native_vlan == 1
34 | assert interface.voice_vlan is None
35 | assert interface.description == ""
36 | assert not interface.bpduguard
37 | assert not interface.type_edge
38 | assert interface.is_enabled
39 |
40 | def test_shutdown(self):
41 | config = ("interface E0\n"
42 | " shutdown")
43 |
44 | interface = netwalk.Interface(config=config)
45 | assert not interface.is_enabled
46 |
47 | def test_unparsed_lines(self):
48 | config = ("interface E0\n"
49 | " switchport mode access\n"
50 | " antani mascetti perozzi")
51 |
52 | interface = netwalk.Interface(config=config)
53 |
54 | assert interface.unparsed_lines == [" antani mascetti perozzi", ]
55 |
56 | def test_description(self):
57 | config = ("interface E0\n"
58 | " description Antani\n")
59 |
60 | interface = netwalk.Interface(config=config)
61 | assert interface.description == "Antani"
62 |
63 | def test_bpduguard(self):
64 | config = ("interface E0\n"
65 | " spanning-tree bpduguard enable\n")
66 |
67 | interface = netwalk.Interface(config=config)
68 | assert interface.bpduguard
69 |
70 | def test_dynamic_desirable(self):
71 | config = ("interface GigabitEthernet0/16\n"
72 | "description [Direct] SD-WAN\n"
73 | "switchport access vlan 820\n"
74 | "switchport mode dynamic desirable\n"
75 | "spanning-tree portfast\n")
76 |
77 | interface = netwalk.Interface(config=config)
78 |
79 | assert interface.mode == "dynamic desirable"
80 | assert interface.native_vlan == 820
81 |
82 |
83 | class AccessInterfaceTester(unittest.TestCase):
84 | def test_mode(self):
85 | config = ("interface E0\n"
86 | " switchport mode access\n")
87 |
88 | interface = netwalk.Interface(config=config)
89 | assert interface.name == "E0"
90 | assert interface.mode == "access"
91 | assert interface.native_vlan == 1
92 |
93 | def test_interface_w_vlan(self):
94 | config = ("interface E0\n"
95 | " switchport mode access\n"
96 | " switchport access vlan 3\n")
97 |
98 | interface = netwalk.Interface(config=config)
99 | assert interface.name == "E0"
100 | assert interface.mode == "access"
101 | assert interface.native_vlan == 3
102 |
103 | def test_interface_w_trunk_native(self):
104 | config = ("interface E0\n"
105 | " switchport mode access\n"
106 | " switchport trunk native vlan 3\n")
107 |
108 | interface = netwalk.Interface(config=config)
109 | assert interface.name == "E0"
110 | assert interface.mode == "access"
111 | assert interface.native_vlan == 1
112 |
113 | def test_interface_portfast(self):
114 | config = ("interface E0\n"
115 | " switchport mode access\n"
116 | " spanning-tree portfast\n")
117 |
118 | interface = netwalk.Interface(config=config)
119 | assert interface.name == "E0"
120 | assert interface.mode == "access"
121 | assert interface.type_edge
122 |
123 | def test_interface_portfast_trunk(self):
124 | config = ("interface E0\n"
125 | " switchport mode access\n"
126 | " spanning-tree portfast trunk\n")
127 |
128 | interface = netwalk.Interface(config=config)
129 | assert interface.name == "E0"
130 | assert interface.mode == "access"
131 | assert not interface.type_edge
132 |
133 | def test_voice_vlan(self):
134 | config = ("interface E0\n"
135 | " switchport mode access\n"
136 | " switchport voice vlan 150\n")
137 |
138 | interface = netwalk.Interface(config=config)
139 | assert interface.name == "E0"
140 | assert interface.mode == "access"
141 | assert interface.native_vlan == 1
142 | assert interface.voice_vlan == 150
143 |
144 |
145 | class TrunkInterfaceTester(unittest.TestCase):
146 | def test_mode(self):
147 | config = ("interface E0\n"
148 | " switchport mode trunk\n")
149 |
150 | interface = netwalk.Interface(config=config)
151 | assert interface.name == "E0"
152 | assert interface.mode == "trunk"
153 | assert interface.native_vlan == 1
154 | assert interface.allowed_vlan == {x for x in range(1, 4095)}
155 |
156 | def test_interface_w_native_vlan(self):
157 | config = ("interface E0\n"
158 | " switchport mode trunk\n"
159 | " switchport trunk native vlan 3\n")
160 |
161 | interface = netwalk.Interface(config=config)
162 | assert interface.name == "E0"
163 | assert interface.mode == "trunk"
164 | assert interface.native_vlan == 3
165 | assert interface.allowed_vlan == {x for x in range(1, 4095)}
166 |
167 | def test_interface_w_allowed_vlan(self):
168 | config = ("interface E0\n"
169 | " switchport mode trunk\n"
170 | " switchport trunk allowed vlan 1,2,3,5,10-12,67,90-95")
171 |
172 | interface = netwalk.Interface(config=config)
173 | assert interface.name == "E0"
174 | assert interface.mode == "trunk"
175 | assert interface.native_vlan == 1
176 | assert interface.allowed_vlan == set(
177 | [1, 2, 3, 5, 10, 11, 12, 67, 90, 91, 92, 93, 94, 95])
178 |
179 | def test_interface_w_multiline_allowed_vlan(self):
180 | config = ("interface E0\n"
181 | " switchport mode trunk\n"
182 | " switchport trunk allowed vlan 1,2,3-5\n"
183 | " switchport trunk allowed vlan add 7,8-10")
184 |
185 | interface = netwalk.Interface(config=config)
186 | assert interface.name == "E0"
187 | assert interface.mode == "trunk"
188 | assert interface.native_vlan == 1
189 | assert interface.allowed_vlan == set(
190 | [1, 2, 3, 4, 5, 7, 8, 9, 10])
191 |
192 |
193 | class TestInterfaceOutString(unittest.TestCase):
194 | def test_base(self):
195 | intdata = {'name': 'E0'}
196 | interface = netwalk.Interface(**intdata)
197 |
198 | outconfig = ('interface E0\n'
199 | ' switchport mode access\n'
200 | ' switchport access vlan 1\n'
201 | ' no shutdown\n'
202 | '!\n')
203 |
204 | assert interface.generate_config(False) == outconfig
205 |
206 | def test_base_full(self):
207 | intdata = {'name': 'E0'}
208 | interface = netwalk.Interface(**intdata)
209 |
210 | outconfig = ('interface E0\n'
211 | ' no description\n'
212 | ' switchport mode access\n'
213 | ' no switchport trunk native vlan\n'
214 | ' no switchport trunk allowed vlan\n'
215 | ' switchport access vlan 1\n'
216 | ' no switchport voice vlan\n'
217 | ' no spanning-tree portfast\n'
218 | ' no spanning-tree bpduguard\n'
219 | ' no shutdown\n'
220 | '!\n')
221 |
222 | assert interface.generate_config(True) == outconfig
223 |
224 | def test_mode_access(self):
225 | intdata = {'name': 'E0',
226 | 'mode': 'access'}
227 | interface = netwalk.Interface(**intdata)
228 |
229 | outconfig = ('interface E0\n'
230 | ' switchport mode access\n'
231 | ' switchport access vlan 1\n'
232 | ' no shutdown\n'
233 | '!\n')
234 |
235 | assert interface.generate_config(False) == outconfig
236 |
237 | def test_mode_access_full(self):
238 | intdata = {'name': 'E0',
239 | 'mode': 'access'}
240 | interface = netwalk.Interface(**intdata)
241 |
242 | outconfig = ('interface E0\n'
243 | ' no description\n'
244 | ' switchport mode access\n'
245 | ' no switchport trunk native vlan\n'
246 | ' no switchport trunk allowed vlan\n'
247 | ' switchport access vlan 1\n'
248 | ' no switchport voice vlan\n'
249 | ' no spanning-tree portfast\n'
250 | ' no spanning-tree bpduguard\n'
251 | ' no shutdown\n'
252 | '!\n')
253 |
254 | assert interface.generate_config(True) == outconfig
255 |
256 | def test_mode_access_native_vlan(self):
257 | intdata = {'name': 'E0',
258 | 'mode': 'access',
259 | 'native_vlan': 3}
260 | interface = netwalk.Interface(**intdata)
261 |
262 | outconfig = ('interface E0\n'
263 | ' switchport mode access\n'
264 | ' switchport access vlan 3\n'
265 | ' no shutdown\n'
266 | '!\n')
267 |
268 | assert interface.generate_config(False) == outconfig
269 |
270 | def test_mode_access_native_vlan_full(self):
271 | intdata = {'name': 'E0',
272 | 'mode': 'access',
273 | 'native_vlan': 3}
274 | interface = netwalk.Interface(**intdata)
275 |
276 | outconfig = ('interface E0\n'
277 | ' no description\n'
278 | ' switchport mode access\n'
279 | ' no switchport trunk native vlan\n'
280 | ' no switchport trunk allowed vlan\n'
281 | ' switchport access vlan 3\n'
282 | ' no switchport voice vlan\n'
283 | ' no spanning-tree portfast\n'
284 | ' no spanning-tree bpduguard\n'
285 | ' no shutdown\n'
286 | '!\n')
287 |
288 | assert interface.generate_config(True) == outconfig
289 |
290 | def test_mode_access_voice_vlan(self):
291 | intdata = {'name': 'E0',
292 | 'mode': 'access',
293 | 'voice_vlan': 150}
294 | interface = netwalk.Interface(**intdata)
295 |
296 | outconfig = ('interface E0\n'
297 | ' switchport mode access\n'
298 | ' switchport access vlan 1\n'
299 | ' switchport voice vlan 150\n'
300 | ' no shutdown\n'
301 | '!\n')
302 |
303 | assert interface.generate_config(False) == outconfig
304 |
305 | def test_mode_access_voice_vlan_full(self):
306 | intdata = {'name': 'E0',
307 | 'mode': 'access',
308 | 'voice_vlan': 150}
309 | interface = netwalk.Interface(**intdata)
310 |
311 | outconfig = ('interface E0\n'
312 | ' no description\n'
313 | ' switchport mode access\n'
314 | ' no switchport trunk native vlan\n'
315 | ' no switchport trunk allowed vlan\n'
316 | ' switchport access vlan 1\n'
317 | ' switchport voice vlan 150\n'
318 | ' no spanning-tree portfast\n'
319 | ' no spanning-tree bpduguard\n'
320 | ' no shutdown\n'
321 | '!\n')
322 |
323 | assert interface.generate_config(True) == outconfig
324 |
325 | def test_mode_trunk_voice_vlan(self):
326 | intdata = {'name': 'E0',
327 | 'mode': 'trunk',
328 | 'voice_vlan': 150}
329 | interface = netwalk.Interface(**intdata)
330 |
331 | outconfig = ('interface E0\n'
332 | ' switchport mode trunk\n'
333 | ' switchport trunk native vlan 1\n'
334 | ' switchport trunk allowed vlan all\n'
335 | ' no shutdown\n'
336 | '!\n')
337 |
338 | assert interface.generate_config(False) == outconfig
339 |
340 | def test_mode_trunk_voice_vlan_full(self):
341 | intdata = {'name': 'E0',
342 | 'mode': 'trunk',
343 | 'voice_vlan': 150}
344 | interface = netwalk.Interface(**intdata)
345 |
346 | outconfig = ('interface E0\n'
347 | ' no description\n'
348 | ' switchport mode trunk\n'
349 | ' no switchport access vlan\n'
350 | ' switchport trunk native vlan 1\n'
351 | ' switchport trunk allowed vlan all\n'
352 | ' no switchport voice vlan\n'
353 | ' no spanning-tree portfast\n'
354 | ' no spanning-tree bpduguard\n'
355 | ' no shutdown\n'
356 | '!\n')
357 |
358 | assert interface.generate_config(True) == outconfig
359 |
360 | def test_trunk(self):
361 | intdata = {'name': 'E0',
362 | 'mode': 'trunk'}
363 | interface = netwalk.Interface(**intdata)
364 |
365 | outconfig = ('interface E0\n'
366 | ' switchport mode trunk\n'
367 | ' switchport trunk native vlan 1\n'
368 | ' switchport trunk allowed vlan all\n'
369 | ' no shutdown\n'
370 | '!\n')
371 |
372 | assert interface.generate_config(False) == outconfig
373 |
374 | def test_trunk_full(self):
375 | intdata = {'name': 'E0',
376 | 'mode': 'trunk'}
377 | interface = netwalk.Interface(**intdata)
378 |
379 | outconfig = ('interface E0\n'
380 | ' no description\n'
381 | ' switchport mode trunk\n'
382 | ' no switchport access vlan\n'
383 | ' switchport trunk native vlan 1\n'
384 | ' switchport trunk allowed vlan all\n'
385 | ' no switchport voice vlan\n'
386 | ' no spanning-tree portfast\n'
387 | ' no spanning-tree bpduguard\n'
388 | ' no shutdown\n'
389 | '!\n')
390 |
391 | assert interface.generate_config(True) == outconfig
392 |
393 | def test_trunk_native(self):
394 | intdata = {'name': 'E0',
395 | 'mode': 'trunk',
396 | 'native_vlan': 3}
397 | interface = netwalk.Interface(**intdata)
398 |
399 | outconfig = ('interface E0\n'
400 | ' switchport mode trunk\n'
401 | ' switchport trunk native vlan 3\n'
402 | ' switchport trunk allowed vlan all\n'
403 | ' no shutdown\n'
404 | '!\n')
405 |
406 | assert interface.generate_config(False) == outconfig
407 |
408 | def test_trunk_native_full(self):
409 | intdata = {'name': 'E0',
410 | 'mode': 'trunk',
411 | 'native_vlan': 3}
412 | interface = netwalk.Interface(**intdata)
413 |
414 | outconfig = ('interface E0\n'
415 | ' no description\n'
416 | ' switchport mode trunk\n'
417 | ' no switchport access vlan\n'
418 | ' switchport trunk native vlan 3\n'
419 | ' switchport trunk allowed vlan all\n'
420 | ' no switchport voice vlan\n'
421 | ' no spanning-tree portfast\n'
422 | ' no spanning-tree bpduguard\n'
423 | ' no shutdown\n'
424 | '!\n')
425 |
426 | assert interface.generate_config(True) == outconfig
427 |
428 | def test_trunk_allowed_vlan(self):
429 | intdata = {'name': 'E0',
430 | 'mode': 'trunk',
431 | 'allowed_vlan': set([1, 2, 3])}
432 | interface = netwalk.Interface(**intdata)
433 |
434 | outconfig = ('interface E0\n'
435 | ' switchport mode trunk\n'
436 | ' switchport trunk native vlan 1\n'
437 | ' switchport trunk allowed vlan 1,2,3\n'
438 | ' no shutdown\n'
439 | '!\n')
440 |
441 | assert interface.generate_config(False) == outconfig
442 |
443 | def test_trunk_allowed_vlan_full(self):
444 | intdata = {'name': 'E0',
445 | 'mode': 'trunk',
446 | 'allowed_vlan': set([1, 2, 3])}
447 | interface = netwalk.Interface(**intdata)
448 |
449 | outconfig = ('interface E0\n'
450 | ' no description\n'
451 | ' switchport mode trunk\n'
452 | ' no switchport access vlan\n'
453 | ' switchport trunk native vlan 1\n'
454 | ' switchport trunk allowed vlan 1,2,3\n'
455 | ' no switchport voice vlan\n'
456 | ' no spanning-tree portfast\n'
457 | ' no spanning-tree bpduguard\n'
458 | ' no shutdown\n'
459 | '!\n')
460 |
461 | assert interface.generate_config(True) == outconfig
462 |
463 | def test_bpduguard(self):
464 | intdata = {'name': 'E0',
465 | 'bpduguard': True}
466 | interface = netwalk.Interface(**intdata)
467 |
468 | outconfig = ('interface E0\n'
469 | ' switchport mode access\n'
470 | ' switchport access vlan 1\n'
471 | ' spanning-tree bpduguard enable\n'
472 | ' no shutdown\n'
473 | '!\n')
474 |
475 | assert interface.generate_config(False) == outconfig
476 |
477 | def test_bpduguard_full(self):
478 | intdata = {'name': 'E0',
479 | 'bpduguard': True}
480 | interface = netwalk.Interface(**intdata)
481 |
482 | outconfig = ('interface E0\n'
483 | ' no description\n'
484 | ' switchport mode access\n'
485 | ' no switchport trunk native vlan\n'
486 | ' no switchport trunk allowed vlan\n'
487 | ' switchport access vlan 1\n'
488 | ' no switchport voice vlan\n'
489 | ' no spanning-tree portfast\n'
490 | ' spanning-tree bpduguard enable\n'
491 | ' no shutdown\n'
492 | '!\n')
493 |
494 | assert interface.generate_config(True) == outconfig
495 |
496 | def test_type_edge_access(self):
497 | intdata = {'name': 'E0',
498 | 'type_edge': True}
499 | interface = netwalk.Interface(**intdata)
500 |
501 | outconfig = ('interface E0\n'
502 | ' switchport mode access\n'
503 | ' switchport access vlan 1\n'
504 | ' spanning-tree portfast\n'
505 | ' no shutdown\n'
506 | '!\n')
507 |
508 | assert interface.generate_config(False) == outconfig
509 |
510 | def test_type_edge_access_full(self):
511 | intdata = {'name': 'E0',
512 | 'type_edge': True}
513 | interface = netwalk.Interface(**intdata)
514 |
515 | outconfig = ('interface E0\n'
516 | ' no description\n'
517 | ' switchport mode access\n'
518 | ' no switchport trunk native vlan\n'
519 | ' no switchport trunk allowed vlan\n'
520 | ' switchport access vlan 1\n'
521 | ' no switchport voice vlan\n'
522 | ' spanning-tree portfast\n'
523 | ' no spanning-tree bpduguard\n'
524 | ' no shutdown\n'
525 | '!\n')
526 |
527 | assert interface.generate_config(True) == outconfig
528 |
529 | def test_type_edge_trunk(self):
530 | intdata = {'name': 'E0',
531 | 'mode': 'trunk',
532 | 'type_edge': True}
533 | interface = netwalk.Interface(**intdata)
534 |
535 | outconfig = ('interface E0\n'
536 | ' switchport mode trunk\n'
537 | ' switchport trunk native vlan 1\n'
538 | ' switchport trunk allowed vlan all\n'
539 | ' spanning-tree portfast trunk\n'
540 | ' no shutdown\n'
541 | '!\n')
542 |
543 | assert interface.generate_config(False) == outconfig
544 |
545 | def test_type_edge_trunk_full(self):
546 | intdata = {'name': 'E0',
547 | 'mode': 'trunk',
548 | 'type_edge': True}
549 | interface = netwalk.Interface(**intdata)
550 |
551 | outconfig = ('interface E0\n'
552 | ' no description\n'
553 | ' switchport mode trunk\n'
554 | ' no switchport access vlan\n'
555 | ' switchport trunk native vlan 1\n'
556 | ' switchport trunk allowed vlan all\n'
557 | ' no switchport voice vlan\n'
558 | ' spanning-tree portfast trunk\n'
559 | ' no spanning-tree bpduguard\n'
560 | ' no shutdown\n'
561 | '!\n')
562 |
563 | assert interface.generate_config(True) == outconfig
564 |
565 |
566 | class TestL3Interface(unittest.TestCase):
567 | import ipaddress
568 |
569 | def test_base_l3_int(self):
570 | config = ("interface Ethernet0\n"
571 | " ip address 10.0.0.1 255.255.255.0\n"
572 | " no shutdown\n"
573 | "!\n")
574 |
575 | interface = netwalk.Interface(config=config)
576 |
577 | addrobject = ipaddress.ip_interface("10.0.0.1/24")
578 | assert addrobject in interface.address['ipv4']
579 | assert interface.address['ipv4'][addrobject]['type'] == 'primary'
580 | assert interface.vrf == "default"
581 |
582 | assert interface.generate_config(False) == config
583 |
584 | def test_l3_int_w_secondary(self):
585 | config = ("interface Ethernet0\n"
586 | " ip address 10.0.0.1 255.255.255.0\n"
587 | " ip address 10.0.1.1 255.255.255.0 secondary\n"
588 | " ip address 10.0.2.1 255.255.255.0 secondary\n"
589 | " no shutdown\n"
590 | "!\n")
591 |
592 | interface = netwalk.Interface(config=config)
593 |
594 | primaddrobject = ipaddress.ip_interface("10.0.0.1/24")
595 | secaddrobject_1 = ipaddress.ip_interface("10.0.1.1/24")
596 | secaddrobject_2 = ipaddress.ip_interface("10.0.2.1/24")
597 |
598 | assert primaddrobject in interface.address['ipv4']
599 | assert secaddrobject_1 in interface.address['ipv4']
600 | assert secaddrobject_2 in interface.address['ipv4']
601 |
602 | assert interface.address['ipv4'][primaddrobject]['type'] == 'primary'
603 | assert interface.address['ipv4'][secaddrobject_1]['type'] == 'secondary'
604 | assert interface.address['ipv4'][secaddrobject_2]['type'] == 'secondary'
605 |
606 | assert interface.generate_config(False) == config
607 |
608 | def test_l3_int_w_hsrp(self):
609 | config = ("interface Ethernet0\n"
610 | " ip address 10.0.0.1 255.255.255.0\n"
611 | " standby 1 ip 10.0.0.2\n"
612 | " no shutdown\n"
613 | "!\n")
614 |
615 | interface = netwalk.Interface(config=config)
616 |
617 | primaddrobject = ipaddress.ip_interface("10.0.0.1/24")
618 | hsrpaddrobj = ipaddress.ip_address("10.0.0.2")
619 |
620 | assert primaddrobject in interface.address['ipv4']
621 | assert interface.address['ipv4'][primaddrobject]['type'] == 'primary'
622 |
623 | assert interface.address['hsrp']['version'] == 1
624 | assert interface.address['hsrp']['groups'][1]['address'] == hsrpaddrobj
625 | assert interface.address['hsrp']['groups'][1]['priority'] == 100
626 | assert interface.address['hsrp']['groups'][1]['preempt'] is False
627 |
628 | assert interface.generate_config(False) == config
629 |
630 | def test_l3_int_w_hsrp_secondary(self):
631 | config = ("interface Ethernet0\n"
632 | " ip address 10.0.0.1 255.255.255.0\n"
633 | " standby 1 ip 10.0.0.2\n"
634 | " standby 1 ip 10.0.0.3 secondary\n"
635 | " no shutdown\n"
636 | "!\n")
637 |
638 | interface = netwalk.Interface(config=config)
639 |
640 | primaddrobject = ipaddress.ip_interface("10.0.0.1/24")
641 | hsrpaddrobj = ipaddress.ip_address("10.0.0.2")
642 |
643 | assert primaddrobject in interface.address['ipv4']
644 | assert interface.address['ipv4'][primaddrobject]['type'] == 'primary'
645 |
646 | assert interface.address['hsrp']['version'] == 1
647 | assert interface.address['hsrp']['groups'][1]['address'] == hsrpaddrobj
648 | assert interface.address['hsrp']['groups'][1]['secondary'] == [
649 | ipaddress.ip_address("10.0.0.3")]
650 | assert interface.address['hsrp']['groups'][1]['priority'] == 100
651 | assert interface.address['hsrp']['groups'][1]['preempt'] is False
652 |
653 | assert interface.generate_config(False) == config
654 |
655 | def test_l3_int_w_hsrp_grp_0(self):
656 | config = ("interface Ethernet0\n"
657 | " ip address 10.0.0.1 255.255.255.0\n"
658 | " standby ip 10.0.0.2\n"
659 | " no shutdown\n"
660 | "!\n")
661 |
662 | interface = netwalk.Interface(config=config)
663 |
664 | primaddrobject = ipaddress.ip_interface("10.0.0.1/24")
665 | hsrpaddrobj = ipaddress.ip_address("10.0.0.2")
666 |
667 | assert primaddrobject in interface.address['ipv4']
668 |
669 | assert interface.address['ipv4'][primaddrobject]['type'] == 'primary'
670 | assert interface.address['hsrp']['groups'][0]['address'] == hsrpaddrobj
671 | assert interface.address['hsrp']['groups'][0]['priority'] == 100
672 | assert interface.address['hsrp']['groups'][0]['preempt'] is False
673 | assert interface.address['hsrp']['version'] == 1
674 |
675 | assert interface.generate_config(False) == config
676 |
677 | def test_l3_int_w_hsrp_w_extra_conf(self):
678 | config = ("interface Ethernet0\n"
679 | " ip address 10.0.0.1 255.255.255.0\n"
680 | " standby version 2\n"
681 | " standby 1 ip 10.0.0.2\n"
682 | " standby 1 priority 120\n"
683 | " standby 1 preempt\n"
684 | " no shutdown\n"
685 | "!\n")
686 |
687 | interface = netwalk.Interface(config=config)
688 |
689 | primaddrobject = ipaddress.ip_interface("10.0.0.1/24")
690 | hsrpaddrobj = ipaddress.ip_address("10.0.0.2")
691 |
692 | assert primaddrobject in interface.address['ipv4']
693 |
694 | assert interface.address['ipv4'][primaddrobject]['type'] == 'primary'
695 | assert interface.address['hsrp']['groups'][1]['address'] == hsrpaddrobj
696 | assert interface.address['hsrp']['groups'][1]['preempt']
697 | assert interface.address['hsrp']['groups'][1]['priority'] == 120
698 | assert interface.address['hsrp']['version'] == 2
699 |
700 | assert interface.generate_config(False) == config
701 |
702 | def test_l3_int_vrf(self):
703 | config = ("interface Ethernet0\n"
704 | " vrf forwarding antani\n"
705 | " ip address 10.0.0.1 255.255.255.0\n"
706 | " no shutdown\n"
707 | "!\n")
708 |
709 | interface = netwalk.Interface(config=config)
710 |
711 | primaddrobject = ipaddress.ip_interface("10.0.0.1/24")
712 |
713 | assert primaddrobject in interface.address['ipv4']
714 | assert interface.vrf == "antani"
715 |
716 | assert interface.generate_config(False) == config
717 |
718 |
719 | class TestPortChannel(unittest.TestCase):
720 | def test_base_po(self):
721 | config = ("interface Ethernet0\n"
722 | " channel-group 1 mode active\n"
723 | " no shutdown\n"
724 | "!\n")
725 |
726 | interface = netwalk.Interface(config=config)
727 |
728 | config = ("interface Port-channel1\n"
729 | " switchport mode trunk\n"
730 | " no shutdown\n"
731 | "!\n")
732 |
733 | po = netwalk.Interface(config=config)
734 |
735 | switch = netwalk.Switch(mgmt_address="1.1.1.1")
736 | switch.add_interface(interface)
737 | switch.add_interface(po)
738 |
739 | interface.parse_config()
740 |
741 | assert interface.parent_interface == po
742 | assert interface in po.child_interfaces
743 |
744 |
745 | class TestSelfFunctions(unittest.TestCase):
746 | def test_add_neighbor(self):
747 | side_a = Interface(name='SideA')
748 | side_b = Interface(name='SideB')
749 |
750 | side_a.add_neighbor(side_b)
751 |
752 | assert side_b in side_a.neighbors
753 | assert side_a in side_b.neighbors
754 |
755 | def test_add_neighbor_twice(self):
756 | side_a = Interface(name='SideA')
757 | side_b = Interface(name='SideB')
758 |
759 | side_a.add_neighbor(side_b)
760 | side_b.add_neighbor(side_a)
761 |
762 | assert side_b in side_a.neighbors
763 | assert side_a in side_b.neighbors
764 |
765 | assert len(side_a.neighbors) == 1
766 | assert len(side_b.neighbors) == 1
767 |
768 |
769 | class TestRouterInterfaces(unittest.TestCase):
770 | def test_encapsulation_dot1q(self):
771 | config = ("interface GigabitEthernet0/0/0\n"
772 | " encapsulation dot1q 10\n"
773 | "!\n")
774 |
775 | testint = Interface(config=config)
776 |
777 | assert testint.mode == "access"
778 | assert testint.native_vlan == 10
779 |
780 | def test_encapsulation_dot1Q(self):
781 | config = ("interface GigabitEthernet0/0/0\n"
782 | " encapsulation dot1Q 99\n"
783 | "!\n")
784 |
785 | testint = Interface(config=config)
786 |
787 | assert testint.mode == "access"
788 | assert testint.native_vlan == 99
789 |
790 | def test_encapsulation_dot1q_native(self):
791 | config = ("interface GigabitEthernet0/0/0\n"
792 | " encapsulation dot1Q 1 native\n"
793 | "!\n")
794 |
795 | testint = Interface(config=config)
796 |
797 | assert testint.mode == "access"
798 | assert testint.native_vlan == 1
799 |
800 |
801 | if __name__ == '__main__':
802 | unittest.main()
803 |
--------------------------------------------------------------------------------
/tests/test_switch.py:
--------------------------------------------------------------------------------
1 | """
2 | netwalk
3 | Copyright (C) 2021 NTT Ltd
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU Affero General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU Affero General Public License for more details.
14 |
15 | You should have received a copy of the GNU Affero General Public License
16 | along with this program. If not, see .
17 | """
18 |
19 | import unittest
20 | import ipaddress
21 | from netwalk import Switch
22 | from netwalk import Interface
23 |
24 |
25 | class TestSwitchBasic(unittest.TestCase):
26 | def test_base_switch(self):
27 | config = ("interface GigabitEthernet0/1\n"
28 | " switchport mode access\n"
29 | "!\n"
30 | "interface GigabitEthernet0/2\n"
31 | " switchport mode access\n"
32 | "!\n")
33 | sw = Switch("192.168.1.1", config=config)
34 |
35 | assert sw.mgmt_address == ipaddress.ip_address("192.168.1.1")
36 | assert len(sw.interfaces) == 2
37 | assert "GigabitEthernet0/1" in sw.interfaces
38 | assert "GigabitEthernet0/2" in sw.interfaces
39 | assert isinstance(sw.interfaces['GigabitEthernet0/1'], Interface)
40 |
41 | def test_get_active_vlans(self):
42 | gi00 = Interface(name="GigabitEthernet0/0",
43 | mode="trunk",
44 | native_vlan=999,
45 | allowed_vlan=set([2, 3, 4, 5]))
46 | gi01 = Interface(name="GigabitEthernet0/1",
47 | mode="access",
48 | native_vlan=111)
49 | sw = Switch("1.1.1.1")
50 | sw.interfaces = {gi00.name: gi00,
51 | gi01.name: gi01}
52 |
53 | vlans = sw.get_active_vlans()
54 | assert vlans == {1, 2, 3, 4, 5, 999, 111}
55 |
56 |
57 | if __name__ == '__main__':
58 | unittest.main()
59 |
--------------------------------------------------------------------------------