如何将密码传递给 bash 中的命令
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5080324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to pass password to a command in bash
提问by jingmin zhang
I want to write a bash script that will execute one command in the script, and the command need read some thing as password. So how can I pass the password to the command in the script?
我想编写一个 bash 脚本来执行脚本中的一个命令,并且该命令需要读取一些东西作为密码。那么如何将密码传递给脚本中的命令呢?
$ota_gen -k $ota_key -i -p $ota_tools $ota_out_file
ota_key is a private key that need to be visited with a password, so how can I do it? thank you.
ota_key 是私钥,需要密码才能访问,请问怎么做呢?谢谢你。
ps: thanks hlovdal for help. expect maybe what can help. But I don't know if it can interact with bash script, such as how to pass parameters from script to expect.
ps:感谢 hlovdal 的帮助。期待也许有什么帮助。但是我不知道它是否可以与bash脚本交互,例如如何从脚本中传递参数到expect。
采纳答案by hlovdal
A quite common tool for feeding programs with proper input (like for instance passwords) non-interactively is the tool expect. The following example is given on the wikipedia page:
以非交互方式为程序提供正确输入(例如密码)的一个非常常见的工具是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
回答by jingmin zhang
OK, I google and get the answer of how to interact with expect in bash script. I have added lines bellow in my script.Ant it tack effect.
好的,我谷歌并得到了如何与 bash 脚本中的 expect 交互的答案。我在我的脚本中添加了以下几行。Ant it tack 效果。
th
日
EXEC=$(expect -c "
spawn $ota_gen -k $ota_key -i -p $ota_tools $ota_out_file
expect \"Enter password for .... key>\"
send \"$PASSWD\r\"
interact
")
echo $EXEC

