简体   繁体   中英

"Cache" credentials on a bash script

I have created a bash script to run a few js scripts into MongoDB. Basically, what I am doing is, running the bash script and passing a parameter in this case called version, example:

./script.sh 1.0

That will go and execute all scripts for the version 1.0. Now, it is possible that MongoDB requires authentication user/pass, so I have an option in the script execution that will ask the user if it requires authentication.

read -p "Username: " mongo_user; read -s -p "Password: " mongo_pass;

My question is: what would be the best way to kind cache the same credentials to call the script multiple times? For example:

./script.sh 1.0
./script.sh 1.1
./script.sh 1.2 and on.. 

I don't want to type in the same credentials every time the script runs.

Caio,

As stated in my comment here's how I did it:
Thanks for Charles Duffy for the printf solution:

#!/bin/bash

ePass() {
        read -sp "Password: " pass
        echo ""
        printf '%s\n' "$pass" | perl -e 'chomp($passwd=<>); chomp($encoded=pack("u",$passwd));print "$encoded\n"' > .pswd
        cat .pswd
}

dPass() {
        dPass=`cat .pswd | perl -e 'chomp($encoded=<>); chomp($passwd=unpack("u",$encoded)); print "$passwd\n"'`
        echo $dPass
}


ePass  
dPass

You can add these functions to your script. When you want to set the password ePass will do:

[KUBO@home ~]$ ./test.sh 
Password: 

It will mask the input to avoid over-the-shoulder reading. Then it will echo the encoded output (remove after testing):

Password: Hello >>> %2&5L;&\`

Then you dPass:

Hello

So when you call your mongo scripts you can use the dPass output as your arg.

  • The best way would be setting an environment variable and reading that variable every time.
comp@rangeesh:~$ export USERNAME=user
comp@rangeesh:~$ export PASSWORD=pass
comp@rangeesh:~$ echo $USERNAME
user
comp@rangeesh:~$ echo $PASSWORD
pass
comp@rangeesh:~$ 

  • using the same way you could use the environment variable for a valid session or global var

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM