1

This is my python function that creates the htpasswd file and adds the username and password in it .

def __adduser(self, passfile, username):

        command=["htpasswd", "-c", passfile, username]
        execute=subprocess.Popen(command, stdout=subprocess.PIPE)
        result=execute.communicate()
        if execute.returncode==0:
            return True
        else:
            #will return the Exceptions instead
            return False

It is working great but the only improvement I want is, how to automate the password entry it ask for after running the scripts that should be set from some variable value

Tara Prasad Gurung
  • 3,422
  • 6
  • 38
  • 76
  • I'd rather look at an existing Python implementation/wrapper than trying to go through a CLI subprocess here… https://pypi.python.org/pypi/htpasswd – deceze Aug 23 '17 at 07:46
  • probably: https://stackoverflow.com/questions/163542/python-how-do-i-pass-a-string-into-subprocess-popen-using-the-stdin-argument – Some1Else Aug 23 '17 at 07:46
  • the problem I got into using the htpasswd is ,the new username get appended if the file already exists. I want just a single file with single entry. that htpasswd cant fulfill – Tara Prasad Gurung Aug 23 '17 at 07:50
  • You basically just want to delete the file, then create a new one. That's what the `-c` flag does. You can do that perfectly fine in Python, even if the PyPi htpasswd library doesn't offer a specific option for that. – deceze Aug 23 '17 at 08:13
  • that is the reason i am using -c there and didn't use the module – Tara Prasad Gurung Aug 23 '17 at 09:13

2 Answers2

1

htpasswd has an -i option:

Read the password from stdin without verification (for script usage).

So:

def __adduser(self, passfile, username, password):
    command = ["htpasswd", "-i", "-c", passfile, username]
    execute = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    execute.communicate(input=password)
    return execute.returncode == 0
Ry-
  • 218,210
  • 55
  • 464
  • 476
0

Use bcrypt python module to create a password

import bcrypt

def encrypt_password(username, password):
    bcrypted = bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt(rounds=12)).decode("utf-8")
    return f"{username}:{bcrypted}"

print(encrypt_password("client", "ClientO98"))

Read more from https://gist.github.com/zobayer1/d86a59e45ae86198a9efc6f3d8682b49

sherin
  • 323
  • 3
  • 10