Giriş: Avtomatlaşdırma = Məlumat + Məntiq

Avtomatlaşdırma skriptinin 70%-i məlumatla işdir: inventarı fayldan oxumaq, API-dən gələn JSON-u açmaq, show çıxışından lazım olanı çəkmək və nəticəni CSV/Excel hesabatına yazmaq. Bu dərsdə məhz bu "yapışqan" bacarıqları öyrənirik.

1. JSON: API-lərin Dili

import json

raw = '''{"hostname": "R1", "interfaces": [
  {"name": "Gi1", "ip": "10.0.0.1", "enabled": true},
  {"name": "Gi2", "ip": null, "enabled": false}]}'''

data = json.loads(raw)                 # str → dict
for i in data["interfaces"]:
    if i["enabled"]:
        print(i["name"], i["ip"])

print(json.dumps(data, indent=2))      # dict → gözəl formatlı str

with open("r1.json", "w") as f:        # fayla
    json.dump(data, f, indent=2)
with open("r1.json") as f:             # fayldan
    data = json.load(f)

Yadda saxlama qaydası: loads/dumps — sətir (s = string), load/dump — fayl. JSON true/null Python-da True/None olur.

2. YAML: İnsan üçün İnventar

# inventory.yaml
defaults:
  device_type: cisco_ios
  username: netadmin
devices:
  - name: CORE-SW1
    host: 10.10.0.1
    role: core
  - name: ACC-SW1
    host: 10.10.0.11
    role: access
  - name: EDGE-R1
    host: 10.10.0.254
    role: edge
    device_type: cisco_xe
import yaml

with open("inventory.yaml") as f:
    inv = yaml.safe_load(f)

devices = [{**inv["defaults"], **d} for d in inv["devices"]]   # defolt + cihaza xas
access = [d for d in devices if d["role"] == "access"]
print([d["name"] for d in access])

{**a, **b} — iki dictionary-ni birləşdirir, b-dəki dəyərlər üstünlük təşkil edir (EDGE-R1 üçün cisco_xe).

3. CSV: Excel ilə Körpü

import csv

# Oxumaq: ilk sətir başlıqdır → hər sətir dict olur
with open("switches.csv", newline="", encoding="utf-8") as f:
    rows = list(csv.DictReader(f))
# [{'hostname': 'SW1', 'ip': '10.0.0.11', 'location': 'Bakı'}, ...]

# Hesabat yazmaq
report = [
    {"hostname": "SW1", "version": "17.9.4", "uptime": "34 days"},
    {"hostname": "SW2", "version": "16.12.10", "uptime": "2 days"},
]
with open("versions.csv", "w", newline="", encoding="utf-8-sig") as f:
    w = csv.DictWriter(f, fieldnames=report[0].keys())
    w.writeheader()
    w.writerows(report)

utf-8-sig — Excel-in Azərbaycan hərflərini (ə, ş, ğ) düzgün göstərməsi üçün. Böyük cədvəllər üçün pandas və openpyxl daha güclüdür.

4. Regex: Mətndən Məlumat Çəkmək

import re

output = """Cisco IOS XE Software, Version 17.09.04a
R1 uptime is 3 weeks, 2 days, 4 hours, 11 minutes
Processor board ID FDO2213A0BC
cisco ISR4331/K9 (1RU) processor"""

version = re.search(r"Version (\S+)", output).group(1)          # 17.09.04a
serial  = re.search(r"Processor board ID (\S+)", output).group(1)
model   = re.search(r"cisco (\S+) \(", output).group(1)          # ISR4331/K9
print(version, serial, model)

# Bütün IP ünvanları
text = "ip address 10.0.0.1 255.255.255.0\nip helper-address 10.0.5.10"
print(re.findall(r"\b(?:\d{1,3}\.){3}\d{1,3}\b", text))

# Adlandırılmış qruplar
m = re.search(r"(?P<intf>\S+) is (?P<status>up|down|administratively down)", "Gi0/1 is administratively down")
print(m.group("intf"), m.group("status"))
SimvolMənası
\d / \S / \srəqəm / boşluq olmayan / boşluq
+ / * / ?1+ / 0+ / 0 və ya 1 dəfə
( )Tutulan qrup — nəticədə qaytarılır
^ / $Sətrin əvvəli / sonu (re.M ilə)

Regex kiçik işlər üçün əladır, amma mürəkkəb cədvəl çıxışları üçün hazır TextFSM şablonları daha etibarlıdır — növbəti dərslərdə.

5. Mini Layihə: IP Planından Konfiqurasiya

# vlans.csv:  vlan,name,network
#            10,MUHASIBAT,10.10.10.0/24
#            20,IT,10.10.20.0/24
import csv, ipaddress

with open("vlans.csv", newline="") as f:
    for row in csv.DictReader(f):
        net = ipaddress.ip_network(row["network"])
        gw = next(net.hosts())                     # ilk istifadə olunan ünvan
        print(f"vlan {row['vlan']}\n name {row['name']}")
        print(f"interface Vlan{row['vlan']}\n ip address {gw} {net.netmask}\n no shutdown\n!")

Nəticə: Excel-dəki IP planı birbaşa SVI konfiqurasiyasına çevrilir. Növbəti addım — bunu Netmiko ilə cihaza göndərmək.