Home > Article > Backend Development > How to Securely Store Username and Password for Python Cron Jobs?
To securely store a username and password combination for use in Python scripts executed by cron jobs, consider the following options:
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:
<code class="python">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')</code>
To store the username separately, abuse the set_password function:
<code class="python">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) </code>
Since items stored in the keyring are encrypted with user credentials, other applications running under the same user account can access the password.
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.
The above is the detailed content of How to Securely Store Username and Password for Python Cron Jobs?. For more information, please follow other related articles on the PHP Chinese website!