how to automate the htpasswd password entry in python scripts
Question:
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
Answers:
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
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
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
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
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