The confusion here is in how input to the shell and the openssl program are handled. When you do this interactively, the shell is reading commands from the terminal (i.e. you), and openssl also reads from the terminal, so whatever you type goes to whatever' listening at the time: the openssl ...
command is read by the shell, and then openssl
starts reading from the terminal, so when you type a001 login ...
, that gets read by the openssl program and sent to the remote server.
In a script, it's different. The shell reads commands from the script, but other programs (like openssl) read from what's called standard input (or stdin), which is usually still the terminal. So the shell reads the line openssl ...
, runs the openssl program, which tries to read input from your terminal. If and when openssl exits, the shell will then read a001 login ...
and try to execute it as a shell command.
What you could to do is supply that a001 login ...
as input to the openssl program. The easiest way to do that is usually with a here-doument, introduced by <<somedelimiter
:
openssl s_client -connect imap.gmail.com:993 -crlf <<EOF
a001 login USER_NAME PASSWORD
EOF
That essentially tells the shell "run this openssl ...
command, and feed the following lines (up to 'EOF') into its stdin".
[EDIT] But that doesn't solve a deeper problem, because all it does is send the login
command, then run out of input, and close the connection. You'd have to include additional commands within the here-document to get it to actually do anything:
openssl s_client -connect imap.gmail.com:993 -crlf <<EOF
a001 login USER_NAME PASSWORD
a001 STATUS INBOX (MESSAGES UNSEEN RECENT)
a001 LIST "INBOX" "*"
EOF
...and then capture the output from it (probably by adding >sometempfile
to the command line), and parse through the output to figure out what's on the server. But what you probably really want to do is to be able to interact with the server (e.g. get a list of new messages and then FETCH
them), and this doesn't really allow that -- your script is sending a fixed command list, rather than sending commands one at a time, looking at the results, and sending more commands based on what it gets back. And that really requires something other than a shell script and openssl -- something with a decent IMAP library (as triplee suggested in a comment).