如何在 python 脚本中自动输入 htpasswd 密码

how to automate the htpasswd password entry in python scripts

这是我的 python 函数,它创建 htpasswd 文件并在其中添加用户名和密码。

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

htpasswdan -i option:

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

所以:

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