简体   繁体   中英

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). 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. 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 .

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


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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