"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Securely Store Username and Password for Python Cron Jobs?

How to Securely Store Username and Password for Python Cron Jobs?

Published on 2024-11-03
Browse:231

How to Securely Store Username and Password for Python Cron Jobs?

Secure Storage of Username and Password in Python for Cron Jobs

To securely store a username and password combination for use in Python scripts executed by cron jobs, consider the following options:

Python keyring Library

The keyring library seamlessly integrates with the CryptProtectData API on Windows and relevant APIs on other platforms. This enables the encryption of data using the user's login credentials. Its simple usage involves:

import keyring

# Define a unique namespace for your application
service_id = 'IM_YOUR_APP!'

# Set the password for a given username
keyring.set_password(service_id, 'dustin', 'my secret password')

# Retrieve the password
password = keyring.get_password(service_id, 'dustin')

To store the username separately, abuse the set_password function:

import keyring

MAGIC_USERNAME_KEY = 'im_the_magic_username_key'

# Username to store
username = 'dustin'

# Store the password and username in the keyring
keyring.set_password(service_id, username, "password")
keyring.set_password(service_id, MAGIC_USERNAME_KEY, username)

# Retrieve username and password
username = keyring.get_password(service_id, MAGIC_USERNAME_KEY)
password = keyring.get_password(service_id, username)  

Since items stored in the keyring are encrypted with user credentials, other applications running under the same user account can access the password.

Obfuscation/Encryption

To enhance security, consider obfuscating or encrypting the password before storing it on the keyring. This adds an extra layer of protection, preventing accidental exposure through automated password retrieval. However, anyone with access to the script's source code could still potentially decrypt the password.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3