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

5

我想编写一个Bash脚本,在脚本中执行一个命令,该命令需要读取密码。那么我该如何将密码传递给脚本中的命令?

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

ota_key是需要密码访问的私钥,那么如何操作呢?

提示:感谢hlovdal的帮助。期望可能会有所帮助。但我不知道它是否可以与Bash脚本交互,例如如何从脚本传递参数给expect。

3个回答

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
甚至可以使用autoexpect创建expect脚本。 - dimba
我尝试了一下,但出现了错误,提示找不到 spawn。那么它能在 bash 脚本中使用吗?我的文件以 #!/bin/bash 开头。 - jingmin zhang

1

好的,我在谷歌上找到了如何在bash脚本中与expect交互的答案。我已经在我的脚本中添加了下面的代码,它起到了作用。

th

    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

1
如果您经常传递敏感信息,最好对其进行加密。 例如,可以这样做:
#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文件中,这将提供一个加密环境变量,您可以在需要秘密的任何地方访问它,并且在创建环境变量时会提示您输入密码。在上面的示例中,密码为“secret”。要访问它,请使用以下命令:
`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中,如果需要,即可快速访问该密码。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接