-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday1_python_network_basics.py
More file actions
311 lines (255 loc) · 11.1 KB
/
day1_python_network_basics.py
File metadata and controls
311 lines (255 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
#!/usr/bin/env python3
"""
=============================================================
60-DAY PYTHON NETWORK AUTOMATION — DAY 1 & 2
Onyedikachi Onwe | Atlas Kenji Ltd
Topic: Python Foundations for Network Engineers
=============================================================
WHAT YOU WILL LEARN TODAY:
- Variables, data types, print
- Lists and dictionaries (used everywhere in networking)
- Loops and if/else logic
- Functions
- Mini-project: Simple subnet calculator
RUN THIS FILE:
python3 day1_python_network_basics.py
=============================================================
"""
# ─────────────────────────────────────────────
# SECTION 1: VARIABLES AND DATA TYPES
# ─────────────────────────────────────────────
print("=" * 55)
print(" SECTION 1: Variables and Data Types")
print("=" * 55)
# Strings — device names, IP addresses, hostnames
hostname = "SW-CORE-01"
ip_address = "192.168.1.1"
vendor = "Cisco"
# Integers — port numbers, VLANs, hop counts
vlan_id = 100
port_number = 22 # SSH port
max_hops = 15 # RIP max hop count
# Floats — bandwidth in Gbps, latency in ms
bandwidth_gbps = 1.0
latency_ms = 2.5
# Booleans — device reachable? interface up?
is_reachable = True
interface_up = True
print(f"Hostname : {hostname}")
print(f"IP Address : {ip_address}")
print(f"Vendor : {vendor}")
print(f"VLAN ID : {vlan_id}")
print(f"SSH Port : {port_number}")
print(f"Reachable : {is_reachable}")
print(f"Interface Up: {interface_up}")
print()
# ─────────────────────────────────────────────
# SECTION 2: LISTS — storing multiple devices
# ─────────────────────────────────────────────
print("=" * 55)
print(" SECTION 2: Lists (Device Inventory)")
print("=" * 55)
# A list of switch IPs in your network
switches = [
"192.168.1.10",
"192.168.1.11",
"192.168.1.12",
"192.168.1.13",
]
routers = [
"10.0.0.1",
"10.0.0.2",
]
print(f"Total switches : {len(switches)}")
print(f"First switch : {switches[0]}") # index starts at 0
print(f"Last switch : {switches[-1]}") # -1 = last item
# Loop through all switches — you'll use this pattern constantly
print("\nAll switches in the network:")
for ip in switches:
print(f" -> {ip}")
# Add a new switch
switches.append("192.168.1.14")
print(f"\nAfter adding new switch, total: {len(switches)}")
print()
# ─────────────────────────────────────────────
# SECTION 3: DICTIONARIES — device profiles
# ─────────────────────────────────────────────
print("=" * 55)
print(" SECTION 3: Dictionaries (Device Profiles)")
print("=" * 55)
# A dictionary stores key-value pairs — perfect for device info
# This is the same structure Netmiko uses to connect to devices!
device = {
"hostname" : "SW-CORE-01",
"ip" : "192.168.1.10",
"vendor" : "cisco",
"model" : "Catalyst 3750",
"os_version" : "IOS 15.2",
"location" : "Server Room - Rack A1",
"port" : 22,
"interfaces" : ["Gi0/1", "Gi0/2", "Gi0/3", "Gi0/4"],
"is_reachable" : True,
}
print(f"Device : {device['hostname']}")
print(f"IP : {device['ip']}")
print(f"Location : {device['location']}")
print(f"Interfaces : {device['interfaces']}")
# Update a value
device["os_version"] = "IOS 15.4"
print(f"Updated OS : {device['os_version']}")
# A list of device dictionaries — your first real inventory!
network_inventory = [
{"hostname": "SW-CORE-01", "ip": "192.168.1.10", "role": "core-switch", "vendor": "cisco"},
{"hostname": "SW-ACC-01", "ip": "192.168.1.11", "role": "access-switch", "vendor": "cisco"},
{"hostname": "SW-ACC-02", "ip": "192.168.1.12", "role": "access-switch", "vendor": "huawei"},
{"hostname": "RTR-EDGE-01","ip": "10.0.0.1", "role": "edge-router", "vendor": "cisco"},
{"hostname": "RTR-EDGE-02","ip": "10.0.0.2", "role": "edge-router", "vendor": "huawei"},
]
print("\nFull Network Inventory:")
print(f" {'HOSTNAME':<16} {'IP':<16} {'ROLE':<16} {'VENDOR'}")
print(f" {'-'*16} {'-'*16} {'-'*16} {'-'*8}")
for d in network_inventory:
print(f" {d['hostname']:<16} {d['ip']:<16} {d['role']:<16} {d['vendor']}")
print()
# ─────────────────────────────────────────────
# SECTION 4: IF / ELSE — decision logic
# ─────────────────────────────────────────────
print("=" * 55)
print(" SECTION 4: If / Else (Device Logic)")
print("=" * 55)
def check_device_status(device_info):
"""Check if a device is reachable and print its status."""
if device_info["is_reachable"]:
print(f" [UP] {device_info['hostname']} ({device_info['ip']}) is online")
else:
print(f" [DOWN] {device_info['hostname']} ({device_info['ip']}) is OFFLINE — alert!")
# Simulate some devices being down
device_statuses = [
{"hostname": "SW-CORE-01", "ip": "192.168.1.10", "is_reachable": True},
{"hostname": "SW-ACC-01", "ip": "192.168.1.11", "is_reachable": False},
{"hostname": "SW-ACC-02", "ip": "192.168.1.12", "is_reachable": True},
{"hostname": "RTR-EDGE-01", "ip": "10.0.0.1", "is_reachable": True},
{"hostname": "RTR-EDGE-02", "ip": "10.0.0.2", "is_reachable": False},
]
print("Device Status Report:")
offline_count = 0
for d in device_statuses:
check_device_status(d)
if not d["is_reachable"]:
offline_count += 1
print(f"\n Summary: {offline_count} device(s) offline out of {len(device_statuses)}")
print()
# ─────────────────────────────────────────────
# SECTION 5: FUNCTIONS — reusable code blocks
# ─────────────────────────────────────────────
print("=" * 55)
print(" SECTION 5: Functions")
print("=" * 55)
def get_device_by_role(inventory, role):
"""
Filter the inventory and return all devices matching a given role.
This is a pattern you will use constantly in automation scripts.
"""
matched = []
for device in inventory:
if device["role"] == role:
matched.append(device)
return matched
def summarise_inventory(inventory):
"""Print a summary count by vendor."""
vendor_count = {}
for device in inventory:
v = device["vendor"]
if v in vendor_count:
vendor_count[v] += 1
else:
vendor_count[v] = 1
return vendor_count
# Use the functions
core_switches = get_device_by_role(network_inventory, "core-switch")
access_switches = get_device_by_role(network_inventory, "access-switch")
edge_routers = get_device_by_role(network_inventory, "edge-router")
print(f"Core switches : {len(core_switches)}")
print(f"Access switches : {len(access_switches)}")
print(f"Edge routers : {len(edge_routers)}")
vendor_summary = summarise_inventory(network_inventory)
print("\nDevices by vendor:")
for vendor, count in vendor_summary.items():
print(f" {vendor:<10} : {count} device(s)")
print()
# ─────────────────────────────────────────────
# MINI-PROJECT: SUBNET CALCULATOR
# (Using Python's built-in ipaddress module)
# ─────────────────────────────────────────────
print("=" * 55)
print(" MINI-PROJECT: Subnet Calculator")
print("=" * 55)
import ipaddress # built-in Python library — no install needed!
def subnet_info(cidr):
"""
Take a CIDR notation like '192.168.1.0/24'
and print full subnet details — useful for planning & docs.
"""
network = ipaddress.IPv4Network(cidr, strict=False)
print(f"\n Network : {network.network_address}")
print(f" Subnet Mask : {network.netmask}")
print(f" Broadcast : {network.broadcast_address}")
print(f" CIDR : /{network.prefixlen}")
print(f" Total IPs : {network.num_addresses}")
print(f" Usable Hosts: {network.num_addresses - 2}")
print(f" First Host : {list(network.hosts())[0]}")
print(f" Last Host : {list(network.hosts())[-1]}")
def is_ip_in_network(ip, cidr):
"""Check if a given IP belongs to a subnet."""
network = ipaddress.IPv4Network(cidr, strict=False)
addr = ipaddress.IPv4Address(ip)
return addr in network
# Test the calculator
print("\n--- Office LAN ---")
subnet_info("192.168.1.0/24")
print("\n--- Management VLAN ---")
subnet_info("10.0.0.0/29") # small /29 — only 6 usable hosts
print("\n--- IP Membership Check ---")
test_cases = [
("192.168.1.50", "192.168.1.0/24"),
("192.168.2.1", "192.168.1.0/24"),
("10.0.0.5", "10.0.0.0/29"),
("10.0.0.10", "10.0.0.0/29"),
]
for ip, net in test_cases:
result = "YES — in subnet" if is_ip_in_network(ip, net) else "NO — not in subnet"
print(f" {ip:<16} in {net:<20} -> {result}")
# ─────────────────────────────────────────────
# WHAT'S NEXT — DAY 3 & 4 PREVIEW
# ─────────────────────────────────────────────
print()
print("=" * 55)
print(" DAY 1-2 COMPLETE!")
print("=" * 55)
print("""
You now know:
[x] Variables, strings, integers, booleans
[x] Lists — storing multiple device IPs
[x] Dictionaries — device profiles (Netmiko format!)
[x] Loops — iterating over all devices
[x] If/else — status checking logic
[x] Functions — reusable automation blocks
[x] ipaddress module — subnet calculations
DAY 3-4 CHALLENGE — try these yourself:
─────────────────────────────────────────
1. Add 3 more devices to network_inventory
with a new role called "firewall"
2. Write a function called get_cisco_devices()
that returns only Cisco devices from the inventory
3. Use subnet_info() to calculate info for:
172.16.0.0/20 (a medium enterprise subnet)
4. Write a function that checks if two IP addresses
are on the same subnet
Hint: use is_ip_in_network() as a starting point
COMING DAY 5-6:
- Reading/writing files (CSV device inventory)
- Parsing real config output from routers
- Saving your subnet reports to a .txt file
Keep going, Onyedikachi. Every line you write
today is a step toward that remote role.
""")