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
0 1 2 |
pip install python-dotenv |
Create .env File
0 1 2 3 4 5 |
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.
0 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 |
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