简体   繁体   English

bash 脚本上的“缓存”凭据

[英]"Cache" credentials on a bash script

I have created a bash script to run a few js scripts into MongoDB.我创建了一个 bash 脚本来在 MongoDB 中运行一些 js 脚本。 Basically, what I am doing is, running the bash script and passing a parameter in this case called version, example:基本上,我正在做的是,运行 bash 脚本并在这种情况下传递一个名为 version 的参数,例如:

./script.sh 1.0

That will go and execute all scripts for the version 1.0.这将执行版本 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.现在,MongoDB 可能需要身份验证用户/密码,所以我在脚本执行中有一个选项,它会询问用户是否需要身份验证。

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:感谢 Charles Duffy 提供printf解决方案:

#!/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:当您想设置密码时,ePass 将执行以下操作:

[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:然后你 dPass:

Hello

So when you call your mongo scripts you can use the dPass output as your arg.因此,当您调用 mongo 脚本时,您可以使用 dPass 输出作为参数。

  • 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使用相同的方式,您可以将环境变量用于有效会话或全局变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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