How to input automatically when running a shell over SSH?

In my shell script I am running a command which is asking me for input.

How can I give the command the input it needs automatically?

For example:

$cat test.sh
ssh-copy-id [email protected]

When running test.sh:

  • First, it will ask:

    Are you sure you want to continue connecting (yes/no)?

  • Then, it will ask me to input the password:

    [email protected]'s password:

Is there a way to input this automatically?


For simple input, like two prompts and two corresponding fixed responses, you could also use a "here document", the syntax of which looks like this:

test.sh <<!
y
pasword
!

The << prefixes a pattern, in this case '!'. Everything up to a line beginning with that pattern is interpreted as standard input. This approach is similar to the suggestion to pipe a multi-line echo into ssh, except that it saves the fork/exec of the echo command and I find it a bit more readable. The other advantage is that it uses built-in shell functionality so it doesn't depend on expect.


For general command-line automation, Expect is the classic tool. Or try pexpect if you're more comfortable with Python.

Here's a similar question that suggests using Expect: Use expect in bash script to provide password to SSH command


There definitely is... Use the spawn, expect, and send commands:

spawn test.sh
expect "Are you sure you want to continue connecting (yes/no)?"
send "yes"

There are more examples all over Stack Overflow, see: Help with Expect within a bash script

You may need to install these commands first, depending on your system.