0

Hi I am new to shell script and I am having trouble using Expect command. I can't get the output for the command I executed in expect block.

I have a ssh script that will connect to a server and check if a log directory exists or not. And if it's not exist, to create one. And if can't create, log the error message.

USER=testuser
IP=101.101.101.101
LOGDIR=/var/aaa/bbb/log

# check directory
sudo ssh -l ${USER} ${IP} ls -ld ${LOGDIR} > /dev/null 2>&1

if [ $? -ne 0 ]; then
  # make directory
  # if error, output log
fi

I want to automate the login process when doing this so I am using expect command as below:

# check directory
PASS=testpassword

expect -c "
  set timeout 5
  spawn ssh -l ${USER} ${IP} ls -ld ${LOGDIR} > /dev/null 2>&1
  expect \"${USER}\'s password:\"
  send \"${PASS}\n\"
  expect \"$\"
"
if [ $? -ne 0 ]; then
  # make directory
  # if error, output log
fi

However, I am unable to retrieve the output from the command of "spawn ssh" line.

How can I get the output from the command inside expect block?

And because I'm not familiar with shell script, a simple code sample will be much appreciated.

Kaung Myat
  • 61
  • 1
  • 5
  • Simpler methods are suggested. Omit checking if the dir exists and run `mkdir -p` unconditionally; there's no error when the dir already exists. Skip sudo unless that's somehow needed. Instead of storing and sending a password, you could copy a `ssh` key to `~testuser/.ssh/authorized_keys` on the server for friendly/no-password ssh sessions. – Milag Jun 02 '20 at 12:33
  • @Milag Thank you for your reply but first I need to check the directory first and create the directory if it doesn't exist. And I need to log that process outputs. Sudo and storing password is also necessary in my case. I wanted to know how to get the output from inside an expect block. – Kaung Myat Jun 02 '20 at 12:42
  • Instead of `command; if [ $? -ne 0 ]` just do `if command;` like `if exec ssh bla bla; then`. `How can I get the output?` from which command. What is that you exactly are trying to do? Why are you using `expect`, can't you use other method of ssh authnetication? – KamilCuk Jun 02 '20 at 13:15
  • From the `spawn` line, looks like all output from `ssh` and descendants are being redirected to your local `/dev/null`; escaping with `\>` might work to redirect `ls` on the server side. Also a silent operation could eliminate the need for redirection, eg `"[ -d $LOGDIR ]; exit $?"` – Milag Jun 02 '20 at 13:59
  • *"I'm not familiar with shell script"* -- you can do all this in [tag:expect] which uses the general purpose language [tag:tcl]. – pynexj Jun 02 '20 at 16:23
  • @ KamilCuk the ssh script was written to connect to a server and check if a log directory exists or not. And every time, I had to login. I wanted to automate that login process. That's why I'm trying to use expect. Maybe my question wasn't clear. I will also try to update the question. – Kaung Myat Jun 03 '20 at 00:19

0 Answers0