ddario
ddario

Reputation: 1035

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?

Upvotes: 1

Views: 2786

Answers (1)

Gilles Qu&#233;not
Gilles Qu&#233;not

Reputation: 185025

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, e.g.

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

Upvotes: 3

Related Questions