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?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With