Python Q&A for Network Engineers

Overview

Q & A

I am often asked questions about how to solve this or that problem, and I decided to post these questions and solutions here, in case it is also useful to someone.

The description of the question can be used as a task and you can first solve it yourself, and then see the solution.

QA Description Topics/modules used in solutions
1 Split the interface configuration into two parts regex, format, jinja2
2 Network Topology Discovery Using CDP/LLDP scrapli, regex, queue, click, rich
3 Filter JSON data by key recursion, generator, regex, click
4 Collect Port Status Information scrapli, concurrent.futures, regex, rich

Q&A 1 Split the interface configuration into two parts

English translation

Надо разбить настройку интерфейса на две части. Есть конфигурация интерфейса такого вида:

set interfaces ae0 unit 1001 description "EXAMPLE_1001"
set interfaces ae0 unit 1001 vlan-tags outer 18
set interfaces ae0 unit 1001 vlan-tags inner 10
set interfaces ae0 unit 1001 family inet policer input P-IN-L2
set interfaces ae0 unit 1001 family inet policer output P-OUT-L2
set interfaces ae0 unit 1001 family inet address 60.1.1.1/30

Эту конфигурацию надо разбить на две части:

set interfaces ae9 unit 1001 description "EXAMPLE_1001"
set interfaces ae9 unit 1001 encapsulation vlan-bridge
set interfaces ae9 unit 1001 vlan-tags outer 18
set interfaces ae9 unit 1001 vlan-tags inner 10
set interfaces ae9 unit 1001 family bridge policer input P-IN-L2
set interfaces ae9 unit 1001 family bridge policer output P-OUT-L2

и

set interfaces irb unit 1001 description "EXAMPLE_1001"
set interfaces irb unit 1001 family inet address 60.1.1.1/30
set interfaces irb unit 1001 mac 00:ff:3c:01:01:01

Подробнее

Q&A 2 Network Topology Discovery Using CDP/LLDP

English translation

Надо обнаружить топологию сети через вывод CDP (считаем что CDP есть на всех устройствах). Для старта должен быть известен IP-адрес одного устройства и параметры подключения по SSH ко всем устройствам в сети.

Надо подключиться к первому устройству, дать команду sh cdp neighbors detail, получить всех соседей и их IP-адреса и подключаться к каждому соседу. На каждом соседе опять дать команду sh cdp neighbors detail и получить соседей этого устройства. Так надо пройтись по всей сети и собрать информацию об устройствах и топологии.

Подробнее

Q&A 3 Filter JSON data by key

English translation

Задача отфильтровать данные из JSON файла по указанному ключу. Технически речь об отборе данных из словаря/списка, так как после чтения данных в Python это уже будет Python list/dict. JSON упоминается потому что именно в этом формате часто очень большая вложенность.

$ python solution_2a.py json_files/cfg.json name
['ae1.185', 'v185', 'ae47.128', 'v128', 'ae1.139', 'v139', 'ae1.140', 'v140', 'User1', 'User2', 'User3', 'ge-0/0/0', '192.168.1.1/29', 11, '10.1.1.1/29', 'ge-0/0/1', '192.168.199.1/30']

$ python solution_2a.py json_files/cfg.json user
[
    [
        {'authentication': {'encrypted-password': 'password'}, 'class': 'super-user', 'name': 'User1', 'uid': 1000},
        {'authentication': {'encrypted-password': 'password'}, 'class': 'super-user', 'name': 'User2', 'uid': 2001},
        {'authentication': {'encrypted-password': 'password'}, 'class': 'super-user', 'name': 'User3', 'uid': 2002}
    ]
]

$ python solution_2a.py json_files/cfg.json user name
['User1', 'User2', 'User3']

Q&A 4 Collect Port Status Information

English translation

Задача собрать информацию о статусе портов на оборудовании (up/down/admin down для Cisco IOS). На первом этапе собирается информация о всех портах (Loopback/физические/Tunnel/...) и их статусе. На втором этапе из собраной информации надо отобрать только физические порты. И на третьем сохранять информацию о статусе портов и добавить возможность сравнивать изменения в статусе портов (текущий статус с последним записанным).

solution_1

solution_1_stats

You might also like...
Python port of Google's libphonenumber

phonenumbers Python Library This is a Python port of Google's libphonenumber library It supports Python 2.5-2.7 and Python 3.x (in the same codebase,

A Python library that provides an easy way to identify devices like mobile phones, tablets and their capabilities by parsing (browser) user agent strings.

Python User Agents user_agents is a Python library that provides an easy way to identify/detect devices like mobile phones, tablets and their capabili

A non-validating SQL parser module for Python

python-sqlparse - Parse SQL statements sqlparse is a non-validating SQL parser for Python. It provides support for parsing, splitting and formatting S

An anthology of a variety of tools for the Persian language in Python

An anthology of a variety of tools for the Persian language in Python

Widevine KEY Extractor in Python

Widevine Client 3 This was originally written by T3rry7f. This repo is slightly modified version of his repo. This only works on standard Windows! Usa

A Python app which can convert normal text to Handwritten text.
A Python app which can convert normal text to Handwritten text.

Text to HandWritten Text ✍️ Converter Watch Tutorial for this project Usage:- Clone my repository. Open CMD in working directory. Run following comman

Etranslate is a free and unlimited python library for transiting your texts

Etranslate is a free and unlimited python library for transiting your texts

py-trans is a Free Python library for translate text into different languages.

Free Python library to translate text into different languages.

a python package that lets you add custom colors and text formatting to your scripts in a very easy way!
a python package that lets you add custom colors and text formatting to your scripts in a very easy way!

colormate Python script text formatting package What is colormate? colormate is a python library that lets you add text formatting to your scripts, it

Owner
Natasha Samoylenko
Natasha Samoylenko
Python character encoding detector

Chardet: The Universal Character Encoding Detector Detects ASCII, UTF-8, UTF-16 (2 variants), UTF-32 (4 variants) Big5, GB2312, EUC-TW, HZ-GB-2312, IS

Character Encoding Detector 1.8k Jan 8, 2023
Fuzzy String Matching in Python

FuzzyWuzzy Fuzzy string matching like a boss. It uses Levenshtein Distance to calculate the differences between sequences in a simple-to-use package.

SeatGeek 8.8k Jan 8, 2023
The Levenshtein Python C extension module contains functions for fast computation of Levenshtein distance and string similarity

Contents Maintainer wanted Introduction Installation Documentation License History Source code Authors Maintainer wanted I am looking for a new mainta

Antti Haapala 1.2k Dec 16, 2022
Paranoid text spacing in Python

pangu.py Paranoid text spacing for good readability, to automatically insert whitespace between CJK (Chinese, Japanese, Korean) and half-width charact

Vinta Chen 194 Nov 19, 2022
An implementation of figlet written in Python

All of the documentation and the majority of the work done was by Christopher Jones ([email protected]). Packaged by Peter Waller <[email protected]>,

Peter Waller 1.1k Jan 2, 2023
Compute distance between sequences. 30+ algorithms, pure python implementation, common interface, optional external libs usage.

TextDistance TextDistance -- python library for comparing distance between two or more sequences by many algorithms. Features: 30+ algorithms Pure pyt

Life4 3k Jan 2, 2023
Python flexible slugify function

awesome-slugify Python flexible slugify function PyPi: https://pypi.python.org/pypi/awesome-slugify Github: https://github.com/dimka665/awesome-slugif

Dmitry Voronin 471 Dec 20, 2022
Python Lex-Yacc

PLY (Python Lex-Yacc) Copyright (C) 2001-2020 David M. Beazley (Dabeaz LLC) All rights reserved. Redistribution and use in source and binary forms, wi

David Beazley 2.4k Dec 31, 2022
Python library for creating PEG parsers

PyParsing -- A Python Parsing Module Introduction The pyparsing module is an alternative approach to creating and executing simple grammars, vs. the t

Pyparsing 1.7k Dec 27, 2022
A simple Python module for parsing human names into their individual components

Name Parser A simple Python (3.2+ & 2.6+) module for parsing human names into their individual components. hn.title hn.first hn.middle hn.last hn.suff

Derek Gulbranson 574 Dec 20, 2022