简体   繁体   English

在bash脚本中等待ssh密码

[英]Wait for ssh password in a bash script

I'm trying to execute commands on a remote machine via ssh, and I need the script to wait until the ssh password is provided (if necessary). 我正在尝试通过ssh在远程计算机上执行命令,我需要脚本等到提供ssh密码(如果需要)。 This my code snippet: 这是我的代码片段:

ssh -T ${remote} << EOF
if [ ! -d $HOME/.ssh ]; then
    mkdir $HOME/.ssh
    touch $HOME/.ssh/authorized_keys
    chmod 0600 $HOME/.ssh/authorized_keys
fi;
EOF

The problem is, commands between EOFs start executing on the local machine without waiting for the pass to be provided. 问题是,EOF之间的命令开始在本地机器上执行而不等待提供传递。 Is there any way to wait for the pass before continuing with the script? 在继续编写脚本之前有没有办法等待传递?

This that simple as : 这很简单:

ssh -T ${remote} << 'EOF'
if [ ! -d $HOME/.ssh ]; then
        `mkdir $HOME/.ssh`
        `touch $HOME/.ssh/authorized_keys`
        `chmod 0600 $HOME/.ssh/authorized_keys`
else
EOF

Note the ' single quotes around EOF . 请注意EOF周围'单引号。

But I recommend you to use $( ) form instead of backticks : the backquote (`) 但我建议你使用$( )形式而不是反引号:反引号(`)

is used in the old-style command substitution, eg 用于旧式命令替换,例如

foo=`command`

The

foo=$(command)

syntax is recommended instead. 建议使用语法。 Backslash handling inside $() is less surprising, and $() is easier to nest. $()内的反斜杠处理不那么令人惊讶,$()更容易嵌套。 See http://mywiki.wooledge.org/BashFAQ/082 http://mywiki.wooledge.org/BashFAQ/082


If you need to pass variables : 如果需要传递变量:

var=42
ssh -T ${remote} << EOF
if [ ! -d \$HOME/.ssh ]; then
        \`mkdir \$HOME/.ssh\`
        \`touch \$HOME/.ssh/authorized_keys\`
        \`chmod 0600 \$HOME/.ssh/authorized_keys\`
else
    echo $var
EOF

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

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