Python Adding Credentials to Scripts

This is a handy Python library to use when credentials are required to be used by scripts. Credentials shouldn’t ever be inside of scripts.
Python-dotenv loads the environment variables from a .env file. The OS module is needed to use these environment variables.

Install

pip install python-dotenv

Create .env File

DEVICE_USERNAME=user
TACACS_DEVICE_PASSWORD=oldtacacs
ADMIN_DEVICE_PASSWORD=Stefan2020
CISCO_DEVICE_PASSWORD=cisco

Use .env in Script

I have used this in my Netmiko Tacacs Project Script. This is a small example section. The full details can be found in the project details or GitHub.

import csv
import pandas as pd
import os
from dotenv import load_dotenv

class csv_devices():

    def __init__(self):
        pass

    def create_device_list(self,csv_data):
        i = 0
        device_list = list()
        ip_list = list()
        for device in csv_data:
            ip,hostname,username = csv_data[i]

            # Load the .env file
            load_dotenv()
            # Assign corerct password for username
            if username == "admin":
                user_pass = os.getenv("ADMIN_DEVICE_PASSWORD")
            elif username == "cisco":
                user_pass = os.getenv("CISCO_DEVICE_PASSWORD") 
            else:
                user_pass = os.getenv("TACACS_DEVICE_PASSWORD")

            # Iterating over the list with the devices ip addresses
            cisco_device = {
                "device_type": "cisco_ios",
                "host": ip,
                "username": username,
                "password": user_pass,
                "port": 22,
                "secret": os.getenv("ENABLE_DEVICE_PASSWORD"),
                "verbose": True
                }
            device_list.append(cisco_device)
            ip_list.append(ip)
            # Add 1 to i for the next device
            i += 1
        return device_list,ip_list

Avoid Adding to Git with .gitignore

Now that the credentials are out of the script, we don’t want to add these to our Git. A .gitignore file is used so Git will not include these files. All we need to do is create the .gitignore file and add the .env file name in there.

Do Include a .env.example with example credentials in

Leave a Comment

Your email address will not be published. Required fields are marked *