如何在bash中将密码传递给命令

时间:2011-02-22 15:43:08

标签: bash passwords

我想编写一个bash脚本,它将在脚本中执行一个命令,并且命令需要读取一些东西作为密码。那么如何将密码传递给脚本中的命令?

$ota_gen -k $ota_key -i $1 -p $ota_tools $2 $ota_out_file

ota_key是需要使用密码访问的私钥,所以我该怎么办? 谢谢。

ps:感谢hlovdal的帮助。 期待可能有所帮助。但我不知道它是否可以与bash脚本进行交互,例如如何将脚本中的参数传递给期望。

3 个答案:

答案 0 :(得分:3)

一种非常常见的工具,用于以非交互方式为具有适当输入(例如密码)的程序提供程序expect。以下示例在维基百科页面上给出:

# Assume $remote_server, $my_user_id, $my_password, and $my_command were read in earlier 
# in the script.
# Open a telnet session to a remote server, and wait for a username prompt.
spawn telnet $remote_server
expect "username:"
# Send the username, and then wait for a password prompt.
send "$my_user_id\r"
expect "password:"
# Send the password, and then wait for a shell prompt.
send "$my_password\r"
expect "%"
# Send the prebuilt command, and then wait for another shell prompt.
send "$my_command\r"
expect "%"
# Capture the results of the command into a variable. This can be displayed, or written to disk.
set results $expect_out(buffer)
# Exit the telnet session, and wait for a special end-of-file character.
send "exit\r"
expect eof

答案 1 :(得分:1)

好的,我谷歌并获得如何与bash脚本中的expect进行交互的答案。 我在我的剧本中添加了一些行。它会增加效果。

    EXEC=$(expect -c "
spawn $ota_gen -k $ota_key -i $1 -p $ota_tools $2 $ota_out_file
expect \"Enter password for .... key>\"
send \"$PASSWD\r\"
interact
")
    echo $EXEC

答案 2 :(得分:0)

如果您正在传递敏感信息并定期使​​用它,您可能最好对其进行加密。

把类似的东西

#create key as follows - will prompt for password
#echo -n 'secret you want encrypted' | openssl enc -aes-256-cbc  -a -salt -pbkdf2|base64
export MY_SECRET='VTJGc2RHVmtYMTlzVnBGWXNYUitLWlpYT3BWdStaQXJXeUVwc1JORnFsNWswZXJKT1dkRWpsWkxLWVFnK1hONQo='

进入您的 .bashrc 将为您提供一个加密的环境变量,您可以在任何需要机密的地方访问该变量,并且系统会提示您输入创建环境变量时使用的密码短语/密码。

在上面的例子中它是“秘密”

你访问它是一个命令如下

`echo $MY_SECRET|base64 --decode|openssl enc -aes-256-cbc -a -d -salt -pbkdf2 `

例如

xfreerpd /parameters.... /p:`echo $MY_SECRET|base64 --decode|openssl enc -aes-256-cbc -a -d -salt -pbkdf2` 

对于 $ota_key 是秘密的查询

$ota_gen -k $ota_key -i $1 -p $ota_tools $2 $ota_out_file

您可以按如下方式创建变量

ota_key=`echo -n 'secret you want encrypted' | openssl enc -aes-256-cbc  -a -salt -pbkdf2|base64`

然后如下使用

$ota_gen -k `echo $ota_key|base64 --decode|openssl enc -aes-256-cbc -a -d -salt -pbkdf2 ` -i $1 -p $ota_tools $2 $ota_out_file

openssh 每次都会提示你输入密码来加密和解密,你可以提供一个作为命令的一部分,但是你只是在历史等中隐藏了一些东西。看看 https://www.tecmint.com/generate-encrypt-decrypt-random-passwords-in-linux/有关为此使用 openssh 的信息。 https://www.serverlab.ca/tutorials/linux/administration-linux/how-to-base64-encode-and-decode-from-command-line/ 用于 base64 和 How to assign an output to a shellscript variable? 用于命令替换的不同选项我在上面使用了反引号 `

PS 添加一个类似的功能

get-key()
{
 echo -n "$1"|base64 --decode|openssl enc -aes-256-cbc -a -d -salt -pbkdf2
}

如果您需要,到您的 bashrc 可让您快速访问秘密