Last active
April 7, 2022 21:20
-
-
Save noize-e/9bb23b962933972d3f475bd00b2f3e6b to your computer and use it in GitHub Desktop.
BerkleyDB client for database creation and user registration
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from passlib.hash import sha512_crypt as sha512 | |
import bsddb3 | |
import string | |
import random | |
import sys | |
""" BerkleyDB Python Client (write & read) | |
unix terminal command to dump a berkley database | |
db_load -T -t hash -f vsftpd-virtual-user.txt vsftpd-virtual-user.db | |
""" | |
class Hashdb(object): | |
def __init__(self, db_name): | |
""" Open the hash format file named filename. | |
Files never intended to be preserved on disk | |
may be created by passing None as the filename. | |
The optional flag identifies the mode used to | |
open the file. It may be: | |
'r' (read only) | |
'w' (read-write) | |
'c' (read-write - create if necessary; the default) | |
'n' (read-write - truncate to zero length). | |
see: https://contest-server.cs.uchicago.edu | |
/ref/python2/library/bsddb.html | |
""" | |
self.db = bsddb3.hashopen(db_name, 'c') | |
def read(self): | |
try: | |
item = self.db.first() | |
print(item) | |
while item: | |
try: | |
item = self.db.next() | |
print(item) | |
except Exception: | |
item = None | |
print("No more items") | |
except bsddb3.db.DBNotFoundError: | |
print("No records") | |
def write(self, key, value): | |
if key not in self.db: | |
# Add user and password to the database | |
self.db[key] = value | |
self.db.sync() | |
return True | |
print("key: {} already exists".format(key)) | |
return False | |
class Password(object): | |
def _random_choice(self): | |
return random.choice(string.ascii_letters + string.digits) | |
def create(self, length=10): | |
""" Generate a string of (n) characters length (random choiced) | |
and get a sha512 crypted hash | |
""" | |
self._value = ''.join(self._random_choice() for i in range(length)) | |
self._hash = str.encode(sha512.hash(self._value)) | |
@property | |
def value(self): | |
return self._value | |
@property | |
def hash(self): | |
return self._hash | |
def main(user): | |
db = Hashdb('vsftpd-virtual-user.db') | |
db.read() | |
pwd = Password() | |
pwd.create() | |
writed = db.write(str.encode(user), pwd.hash) | |
if writed: | |
print("User: {}".format(user)) | |
print("Password: {}".format(pwd.value)) | |
if __name__ == '__main__': | |
main(sys.argv[1]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment