Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to input automatically when running a shell over SSH?

Tags:

shell

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?

like image 387
camino Avatar asked Jan 31 '12 06:01

camino


People also ask

How do I trigger a shell script remotely?

If you plan to scp files and/or run commands via SSH in a script, make sure to set up SSH authentication using public keys. That way you won't be prompted to login, and the script will be much more 'script-like' (non interactive). Show activity on this post.

How do I prompt input in shell?

You can use the built-in read command ; Use the -p option to prompt the user with a question. It should be noted that FILEPATH is the variable name you have chosen, and is set with the answer to the command prompt.


2 Answers

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.

like image 167
Marc Cohen Avatar answered Oct 21 '22 10:10

Marc Cohen


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

like image 22
jjlin Avatar answered Oct 21 '22 11:10

jjlin