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,176
  • 5
  • 30
  • 72
  • 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

1 Answers1

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-
  • 209,133
  • 54
  • 439
  • 449