pythonsubprocess.htpasswd

how to automate the htpasswd password entry in python scripts


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


Solution

  • 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