Tuesday, April 25, 2017

Small bash script to create or reset nginx reverse proxy protected password




Create a file /etc/nginx/listofuser

say it contains username

user1
user2
user3

Then, create a hidden file /etc/nginx/.users


Create a bash script and put it at cron, say daily so once run, it will reset the proxy password to daily and email the result to users on the list with CC on admin.


##############################################################################
#!/bin/bash


for USERNAME in `cat /etc/nginx/listofusers`
do
#Random Pass generation using openssl
RANPASS=`openssl rand -base64 32 | sha256sum | base64 | head -c 8 ; echo`

#htpasswd command
/usr/bin/htpasswd -b /etc/nginx/.users $USERNAME $RANPASS

#email the results to users
echo -e "USER: $USERNAME \nPASSWORD: $RANPASS \n \nPlease login at https://myproxy.example.com \n \nNote: Please expect email notification that it has been changed at the end of the day" | mail -s "password changed at myproxy on `date`" -r noreply@example.com $USERNAME@example.com,admin@example.com

done
###############################################################################

or if you want to load it at command line only and output the user and pass and check the file  /etc/nginx/.users, see below


#################################################################
#!/bin/bash
for USERNAME in `cat /etc/nginx/listofusers`
do

#Random pass generation using openssl (found it by googling)
RANPASS=`openssl rand -base64 32 | sha256sum | base64 | head -c 8 ; echo`

#htpasswd command
/usr/bin/htpasswd -b /etc/nginx/.users $USERNAME $RANPASS

#display the output after execution
echo "USER: $USERNAME"
echo "PASSWORD: $RANPASS"

done
#################################################################

[root@localhost ~]# /usr/local/bin/test.sh
Updating password for user user1
USER: user1
PASSWORD: ZTkxMTQ0
Updating password for user user2
USER: user2
PASSWORD: ZDc4MTMz
Updating password for user user3
USER: user3
PASSWORD: NTIwOGUx



Below are encrypted password file per htpasswd default encryption (CRYPT)

[root@localhost ~]# cat /etc/nginx/.users
user1:$apr1$HJ7/Q/qG$UTO3KujLj3rkANcNpHked1
user2:$apr1$uk59ZMD4$c4zjvMXarVK9zI7nKthz60
user3:$apr1$iIOsYmbh$GdKdkMjwfi4VEHfwTnER60





Below is the portion where you will set on your nginx config under location parameter

    auth_basic "Protected";
    auth_basic_user_file /etc/nginx/.users;