Automating Tasks with Python


Why Automate Tasks?

  • Why automate tasks:
    • Efficiency and time savings
      • automate repetitive tasks to save time
    • Consistency
      • ensures consistency in task execution
    • Scalability
    • Task complexity
      • simplifies handling complex tasks
    • Interoperability
      • integrates well with different technologies and platforms
    • Scripting and Automation APIs
    • Community support
    • Cost savings
    • Adaptability and future-proofing
    • Documentation and auditability

Configuration Management

  • Configuration management can be automated using Python by leveraging libraries and frameworks
    • popular tool is Netmiko
      • a multi-vendor library for managing network devices

Example

Using Python and Netmiko to automate the configuration of a network device.

from netmiko import ConnectHandler
 
# Define the device parameters
device = {
    'device_type': 'cisco_ios',
    'ip': '192.168.1.1',
    'username': 'admin',
    'password': 'password',
    'secret': 'enable_password',
}
 
# Connect to the device
net_connect = ConnectHandler(**device)
net_connect.enable()
 
# Define the configuration commands
interface_config = [
    'interface GigabitEthernet0/0',
    'ip address 192.168.2.1 255.255.255.0',
    'no shutdown',
    'exit',
]
 
# Send configuration commands to the device
output = net_connect.send_config_set(interface_config)
 
# Display the output
print(output)
 
# Disconnect from the device
net_connect.disconnect()
  1. The device dictionary contains information about the network device, such as its type, IP address, and login credentials.
  2. The script uses Netmiko to connect to the device (ConnectHandler), enable privileged exec mode, and define a list of configuration commands for a specific interface.
  3. The send_config_set method sends the configuration commands to the device, and the output is captured.
  4. The output is printed, displaying the results of the configuration commands.
  5. Finally, the script disconnects from the network device.

Task Scheduling

Task scheduling in Python can be automated using the schedule library, which provides a simple interface for scheduling and running periodic tasks.

pip install schedule

Example

import schedule
import time
 
def my_task():
    print("Executing my_task at", time.strftime("%Y-%m-%d %H:%M:%S"))
 
# Schedule the task to run every 1 minute
schedule.every(1).minutes.do(my_task)
 
# Alternatively, you can schedule the task using a cron-like syntax
# schedule.every().hour.at(":30").do(my_task)
 
# Run the scheduler continuously
while True:
    schedule.run_pending()
    time.sleep(1)
  1. The schedule library is imported.
  2. The my_task function is defined, which prints a message indicating when it’s executed.
  3. The schedule.every(1).minutes.do(my_task) line schedules the my_task function to run every 1 minute. You can adjust the scheduling interval based on your needs.
  4. The script enters a loop (while True) where schedule.run_pending() checks if any scheduled tasks need to be executed and then sleeps for 1 second.

Cloud Automation

Cloud automation using Python can be achieved through the use of cloud provider SDKs (Software Development Kits) or APIs (Application Programming Interfaces).

  • e.g., Boto3 library, the official Python SDK for Amazon Web Services (AWS)
pip install boto3

Example

Create an S3 Bucket

import boto3
 
# AWS credentials (replace with your own credentials)
aws_access_key = 'YOUR_ACCESS_KEY'
aws_secret_key = 'YOUR_SECRET_KEY'
region_name = 'us-east-1'
 
# Create an S3 client
s3 = boto3.client('s3', aws_access_key_id=aws_access_key, aws_secret_access_key=aws_secret_key, region_name=region_name)
 
# Specify the bucket name
bucket_name = 'my-unique-bucket-name'
 
# Create an S3 bucket
try:
    response = s3.create_bucket(Bucket=bucket_name)
    print(f"Bucket '{bucket_name}' created successfully.")
except Exception as e:
    print(f"Error creating bucket: {e}")
  1. Replace YOUR_ACCESS_KEY and YOUR_SECRET_KEY with your AWS access key and secret key.
  2. The script uses the Boto3 library to create an S3 client with the specified credentials and region.
  3. It specifies a unique bucket name and attempts to create an S3 bucket using s3.create_bucket().