Learn how to create and manage .htpasswd files for Apache authentication using Python.
Python, with the help of the `passlib` library, can generate and manage .htpasswd files. This is useful for Apache HTTP server authentication, allowing you to programmatically add, remove, or verify users.
First, ensure that you have `passlib` installed in your environment:
pip install passlib
Use the following Python script to create a new .htpasswd file with a username and a password:
from passlib.apache import HtpasswdFile # Create a new .htpasswd file ht = HtpasswdFile('.htpasswd', new=True) ht.set_password('myUsername', 'myPassword') ht.save()
To add a new user to an existing .htpasswd file, use the following script:
from passlib.apache import HtpasswdFile # Load an existing .htpasswd file, or create it if it doesn't exist ht = HtpasswdFile('.htpasswd', new=False) ht.set_password('newUser', 'newPassword') ht.save()