djechlin djechlin - 2 months ago 15
Bash Question

openssl pass first few lines from script then read from stdin

I want to run

openssl
and have it begin with the following commands sent to the server:

t authenticate <dynamically generated base64 string from calling script>
t select Inbox


Then from there take input from
stdin
. I'm very ignorant in shell scripting and the openssl toolkit, and I certainly don't see how to do this simply with piping / redirecting
stdin
unless perhaps I tried setting up a file that was simultaneously drawing from
stdin
itself, or such.

I'm not exactly sure the technologies openssl uses to read its input. For example the following:

$ echo "t login testacct@yahoo.com password" | openssl s_client -connect imap.mail.yahoo.com:993


Does not do the same thing as

openssl s_client -connect imap.mail.yahoo.com:993
# openssl dialogue opens...
C: t login testacct@yahoo.com password
S: t NO [AUTHENTICATIONFAILED] Incorrect username or password. (#YSH002)


I imagine
openssl
is opening a new shell session (I'm weak in my understanding here) and it does not pass its arguments from
stdin
to the inner shell it creates.

Answer

I'd recommend splitting the problem into two scripts:

Firstly you have one script that echoes the initial commands that you want to send and then reads from stdin and writes to stdout. Like this (call it script1.sh for instance):

#!/bin/bash
echo "first command"
echo "second command"
while read x
do
  echo "$x"
done

The second script then just bundles the arguments to openssl so you don't have to keep typing them (call this script2.sh for instance. Note that as with script1.sh above, you should have the #!/bin/bash on the first line to tell the OS that it's a bash script.

then you can just type:

script1.sh | script2.sh

and you'll get the first two lines passed to openssl and then everything you type will get passed after that. If you want to always finish with a few commands you can add them after the while loop in script1.sh.

You terminate the whole thing with Ctrl-D

If openssl echoes the input you type then you will get the lines you type in shown twice (which is a bit irritating). In that case the "-s" argument to "read" will suppress the first line (useful for typing passwords for instance)

Note that this solution is similar to the solution suggested earlier with the temporary file and the tail -f but it avoids the need for a temporary file and everything is done in a single line.

The problem with the solution given in the question is that stdin to the openssl command is closed when the 'echo "t login ..."' command finishes and this will generally cause programs to exit. With the solution given here the pipe connects the stdout of the first script to the stdin of the second and everything typed into read will get passed on to openssl

Comments