Reputation: 53
I would like to do following:
I have a bash script that calls an interactive command that asks the user for a passphrase. I want to specify the passphrase in the script as a variable, and pass that variable to the command non-interactively.
Upvotes: 3
Views: 5891
Reputation: 7910
Lets assume that your script is this(genrsa.sh):
#!/bin/sh
ssh-keygen -t rsa
Normally, if you execute the genrsa.sh file it will ask for a file name and passphrase twice. Like that:
$./genrsa.sh
Enter file name (/root/.ssh/id_rsa):
Enter passphrase(empty for no passphrase:mypassword
Enter same passphrase:mypassword
public key generated, bla bla bla...
$
You want to change the script in a way so you can pass your passphrase as a parameter. So it won't wait for you to type. You will use it like that:
$./genrsa.sh mypassword
To do that, you have to change your script to something like that(genrsa2.sh):
#!/bin/sh
passphrase=$1
set timeout 2
ssh-keygen -t rsa
expect \"Enter file\" { send \"\r\" }
expect \"empty for\" { send \"$passphrase\r\" }
expect \"same passphrase\" { send \"$passphrase\r\" }
Upvotes: 1
Reputation: 1525
Here is a very basic technique. Provide an input file to the script. It is a good choice if you don't want to modify the script itself.
I have to use an example that I dreamed up myself. Here's a basic script prompting the user for values, call it scp
:
#!/bin/bash
echo -n "Type something: "
read X
echo You gave: $X
echo -n "Type something again: "
read Z
echo This time gave: $Z
You can provide an input file as such, call it input
:
value for X
value for Z
Then to invoke the script providing input
for input to the script do this:
cat input | ./scp
..or alternatively and concisely:
./scp < input
The output looks like this:
Type something: You gave: value for X
Type something again: This time gave: value for Z
Upvotes: 1
Reputation: 414
${2:-defaultvalue}
Where 2 (could be the 1st parameter too) is the second positional parameter and "defaultvalue" is the value the variable takes in case you don't specify any value.
Upvotes: -2
Reputation: 3437
I believe you would like to look into expect. This utility is designed specifically for typing on behalf of the user.
Assuming your script has a prompt (or a line that dependably appears before user interaction is required), expect can parse the output, and when it sees the line, e.g., 'passphrase:', enter your passphrase and continue execution of the script.
Upvotes: 4