Automating Network Configuration with Python
Tags: python, networking, git, linux
Published: 2024-05-03 10:23:34

In the world of networking, configuration of network devices can be a tedious task, especially when dealing with a large number of devices or complex network architectures. To simplify this process, I've developed a Python-based automation tool that streamlines the configuration of network devices.

## Introducing the Network Configuration Automator
The Network Configuration Automator is a tool designed to automate the process of configuring network devices. It uses SSH to connect to devices, sends a list of configuration commands, handles exceptions, and disconnects after execution. This tool aims to reduce manual effort and potential errors, making network configuration a breeze.

## Python Script

Additional Stats: This Python script uses the Netmiko library to connect to a network device, send configuration commands, and handle any exceptions that occur during this process.

```
from netmiko import ConnectHandler

# Function to connect to a network device
def connect_to_device(device_info):
    try:
        connection = ConnectHandler(**device_info)
        print(f"Connected to {device_info['host']}")
        return connection
    except Exception as e:
        print(f"Failed to connect to {device_info['host']}: {str(e)}")
        print("Common causes of this problem are:")
        print("1. Incorrect hostname or IP address.")
        print("2. Wrong TCP port.")
        print("3. Intermediate firewall blocking access.")
        print(f"Device settings: {device_info['device_type']} {device_info['host']}:{device_info.get('port', 22)}")
        return None

# Function to send configuration commands to a device
def configure_device(connection, commands):
    try:
        output = connection.send_config_set(commands)
        print(output)
        print("Configuration applied successfully.")
    except Exception as e:
        print(f"Failed to configure device: {str(e)}")

# Main function
def main():
    # Device information (example - replace with actual device details)
    device_info = {
        'device_type': 'cisco_ios',
        'host': '192.168.1.1',
        'username': 'admin',
        'password': 'password',
    }

    # Sample configuration commands (replace with actual configuration)
    commands = [
        'interface GigabitEthernet0/1',
        'description Connection to LAN',
        'ip address 192.168.1.1 255.255.255.0',
        'no shutdown',
        'exit'
    ]

    # Connect to the device
    connection = connect_to_device(device_info)
    if connection:
        # Apply configuration to the device
        configure_device(connection, commands)
        # Disconnect from the device
        connection.disconnect()

if __name__ == "__main__":
    main()
```

## Script Output

NOTE: This is with an imaginary Hostname/IP Address and other credit. Allocating system information may cause vulnerability so it is requested to secure your system.

Tips: Duty should be correcting/verifying hostname or IP address, TCP port and firewall blocking access.

```
Failed to connect to 192.168.1.1: TCP connection to device failed.

Common causes of this problem are:
1. Incorrect hostname or IP address.
2. Wrong TCP port.
3. Intermediate firewall blocking access.

Device settings: cisco_ios 192.168.1.1:22


Common causes of this problem are:
1. Incorrect hostname or IP address.
2. Wrong TCP port.
3. Intermediate firewall blocking access.
Device settings: cisco_ios 192.168.1.1:22
```

## Key Features
The Network Configuration Automator comes with several key features:

`*SSH Connection:*` The tool connects to a network device using SSH, a secure protocol used for remote device management.

> To generate an SSH key for your GitLab project, you can follow these steps:

Open Terminal.

Generate a new SSH key using your email as a label. Replace "your_email@example.com" with your actual email address:

```
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
```

When you're prompted to "Enter a file in which to save the key," press Enter. This accepts the default file location.

```
Enter a file in which to save the key (/Users/you/.ssh/id_rsa): [Press enter]
```

At the prompt, type a secure passphrase. Or for no passphrase, just press Enter.

```
Enter passphrase (empty for no passphrase): [Type a passphrase]
Enter same passphrase again: [Type passphrase again]
```

Start the ssh-agent in the background:

```
eval "$(ssh-agent -s)"
```
Add your SSH private key to the ssh-agent:

```
ssh-add -K ~/.ssh/id_rsa
```

Now you need to add the SSH key to your GitLab account. First, copy the SSH key to your clipboard:

```
pbcopy < ~/.ssh/id_rsa.pub
```

Log into your GitLab account, go to your profile settings, SSH Keys, and paste your key into the "Key" field and click "Add key".

Now you should be able to connect to GitLab via SSH.

`*Command Execution:*` It sends a list of configuration commands to the device. This can be customized based on the specific configuration requirements of your network device.


> Commands & steps to push your code to your GitLab repository:

First, navigate to the directory containing your project in the terminal. You can do this with the cd command:

```
cd /path/to/your/project
```

Initialize a new Git repository in this directory (if you haven't already) with the git init command:

```
git init
```

Add all the files in your project to the Git repository with the git add command:

```
git add .
```

Commit your changes with the git commit command. This saves a snapshot of your project at this point:

```
git commit -m "Initial commit"
```

Now, go to GitLab and create a new repository. After creating the repository, GitLab will show you a URL for the repository. It will look something like this: 

```
https://gitlab.com/username/repository.git.
```
Back in your terminal, add this URL as a remote repository with the git remote add command:

```
git remote add origin https://gitlab.com/username/repository.git
```

Finally, push your code to the GitLab repository with the git push command:

```
git push -u origin master
```

Replace https://gitlab.com/username/repository.git with the actual URL of your GitLab repository. After running these commands, your code should be in your GitLab repository.

> To push your local project to the GitHub repository, you can follow these steps:

Navigate to your project directory in your terminal.

Initialize the local directory as a Git repository, if you haven't done so already:

```
git init
```

Add all the files in your local repository. This stages them for the first commit:

```
git add .
```

Commit the files that you've staged:

```
git commit -m "First commit"
```

At the top of your GitHub repository's Quick Setup page, click the clipboard icon to copy the remote repository URL.

In Terminal, add the URL for the remote repository where your local repository will be pushed:

```
git remote add origin https://github.com/username/repository.git
```

Push the changes in your local repository to GitHub:

```
git push -u origin main
```

Remember to replace main with your branch name if you're not using main as your default branch. If you encounter any issues, make sure you have the necessary permissions to push to the repository.

`*Exception Handling:*` The tool is designed to handle exceptions and print error messages. This ensures that any issues encountered during the configuration process are clearly communicated to the user.

`*Automatic Disconnection:*` After sending the commands, the tool automatically disconnects from the device. This helps maintain the security and integrity of the network device.

## Usage
To use the Network Configuration Automator, you need to have Python installed on your machine. Once you've cloned the repository from GitHub, you can run the script from your terminal. The tool will prompt you to enter the necessary details such as the device IP address, SSH credentials, and the list of commands to execute.

## Conclusion
Automating network configuration can save a significant amount of time and effort, especially in large-scale networks. The Network Configuration Automator is a step towards making this process more efficient and error-free. Whether you're a network engineer looking for ways to improve your workflow, or a Python enthusiast interested in networking, this tool provides a practical application of Python in the networking domain.

### Social
[𝕏](https://twitter.com/niladrridas)
[GitLab](https://gitlab.com/niladridas)
[GitHub](https://github.com/niladrridas)
[LinkedIn](https://linkedin.com/in/niladrridas)
[YouTube](https://www.youtube.com/@niladrridas)