Viewing file: htpasswd.py (2.15 KB) -rw-r--r-- Select action/file-type: (+) | (+) | (+) | Code (+) | Session (+) | (+) | SDB (+) | (+) | (+) | (+) | (+) | (+) |
# coding=utf-8
# Copyright © Cloud Linux GmbH & Cloud Linux Software, Inc 2010-2019 All Rights Reserved # # Licensed under CLOUD LINUX LICENSE AGREEMENT # http://cloudlinux.com/docs/LICENSE.TXT from __future__ import absolute_import import os import random import crypt
__author__ = "Eli Carter"
class HtpasswdDoesNotExists(Exception): pass
def salt(): """ Returns a string of 2 randome letters """ letters = 'abcdefghijklmnopqrstuvwxyz' \ 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' \ '0123456789/.' return random.choice(letters) + random.choice(letters)
class HtpasswdFile(object): """ A class for manipulating htpasswd files. """
def __init__(self, filename, create=False): self.entries = [] self.filename = filename if not create: if os.path.exists(self.filename): self.load() else: raise HtpasswdDoesNotExists("%s does not exist" % self.filename)
def load(self): """ Read the htpasswd file into memory. """ lines = open(self.filename, 'r').readlines() self.entries = [] for line in lines: username, pwhash = line.split(':') entry = [username, pwhash.rstrip()] self.entries.append(entry)
def save(self): """ Write the htpasswd file to disk """ open(self.filename, 'w').writelines(["%s:%s\n" % (entry[0], entry[1]) for entry in self.entries])
def update(self, username, password): """ Replace the entry for the given user, or add it if new. """ pwhash = crypt.crypt(password, salt()) matching_entries = [entry for entry in self.entries if entry[0] == username] if matching_entries: matching_entries[0][1] = pwhash else: self.entries.append([username, pwhash])
def delete(self, username): """ Remove the entry for the given user. """ self.entries = [entry for entry in self.entries if entry[0] != username]
|