Python Basics: Functions and File Handling
Learn essential Python functions and file handling for network automation. Covers creating reusable configuration functions, reading device lists from CSV/text files, and saving show command output to files with practical networking examples.
When building network automation scripts, two Python concepts become absolutely essential: functions and file handling. Functions let you write reusable code blocks for repetitive tasks, while file handling allows you to read device lists and save command outputs. Let's explore both concepts with practical networking examples.
Writing Python Functions for Network Tasks
Functions are reusable blocks of code that perform specific tasks. In network automation, you'll often repeat the same configuration steps across multiple devices. Here's how to create a basic function:
python
def configure_interface(interface_name, ip_address, subnet_mask):
config_commands = [
f"interface {interface_name}",
f"ip address {ip_address} {subnet_mask}",
"no shutdown"
]
return config_commands
# Using the function
vlan10_config = configure_interface("GigabitEthernet0/1", "192.168.10.1", "255.255.255.0")
print(vlan10_config)This function takes three parameters and returns a list of configuration commands. The def keyword defines the function, followed by its name and parameters in parentheses. The return statement sends data back to whoever called the function.
For more complex tasks, you can create functions that connect to devices and execute commands:
python
def get_interface_status(device_ip, username, password):
# This would contain your SSH connection logic
# and return interface status information
return interface_dataReading Files in Python
Network engineers constantly work with device lists stored in text or CSV files. Python's file handling makes this straightforward. Let's start with reading a simple text file containing device IP addresses:
python
# Reading a text file with device IPs
def read_device_list(filename):
device_list = []
with open(filename, 'r') as file:
for line in file:
device_list.append(line.strip())
return device_list
# Usage
devices = read_device_list('network_devices.txt')
print(devices)The with open() statement automatically handles file opening and closing. The 'r' parameter means "read mode," and strip() removes any whitespace or newline characters from each line.
For CSV files containing more detailed device information, use Python's built-in CSV module:
python
import csv
def read_device_csv(filename):
devices = []
with open(filename, 'r') as file:
csv_reader = csv.DictReader(file)
for row in csv_reader:
devices.append({
'hostname': row['hostname'],
'ip_address': row['ip_address'],
'device_type': row['device_type']
})
return devices
# Usage
network_devices = read_device_csv('devices.csv')Writing Files to Save Output
After collecting show command output from devices, you need to save this data for analysis or documentation. Python makes writing to files equally simple:
python
def save_show_output(filename, device_name, command_output):
with open(filename, 'a') as file: # 'a' means append mode
file.write(f"=== {device_name} ===\n")
file.write(command_output)
file.write("\n" + "="*50 + "\n\n")
# Usage
interface_output = "GigabitEthernet0/1 is up, line protocol is up..."
save_show_output('interface_status.txt', 'Router01', interface_output)The 'a' parameter opens the file in append mode, adding new content to the end. Use 'w' for write mode if you want to overwrite the entire file.
Combining Functions and File Handling
Here's a practical example that combines both concepts - a script that reads a device list and saves configuration backup:
python
def backup_device_config(device_ip):
# Simulate getting config from device
config = f"! Configuration for {device_ip}\nhostname Router_{device_ip.split('.')[-1]}\n"
return config
def process_device_list(device_file, backup_dir):
devices = read_device_list(device_file)
for device in devices:
config = backup_device_config(device)
backup_filename = f"{backup_dir}/backup_{device.replace('.', '_')}.txt"
with open(backup_filename, 'w') as file:
file.write(config)
print(f"Backup completed for {device}")
# Usage
process_device_list('devices.txt', 'backups')What's Next
Now that you understand functions and file handling, you're ready to tackle error handling and exception management in Python. These concepts become crucial when dealing with network devices that might be unreachable or return unexpected responses - topics we'll cover in our next post about robust network automation scripts.