Version 1 of executing shell script on remote host using expect

Updated 2012-11-02 01:16:19 by RLE

I am trying to execute a shell script on a computer I have logged into via ssh using expect.

I use this on my localhost to run expect:

#!/bin/bash
HOST=192.168.1.2
USER=”chitti”
PASS=”123″
CMD="./shell_script.sh"

XYZ=$(expect -c “
spawn ssh $USER@$HOST
expect \”password:\”
send \”$PASS\r\”
expect \”\\\\$\”
send \”$CMD\r\”
expect -re \”$USER.*\”
send \”logout\”
“)

echo “$XYZ”

The shell script runs some commands and at the end of the script creates a gzipped archive with the data collected. However, the program is creating the archive before all the commands in the shell script have executed, and I get a an error message when I try to unarchive.

gzip: stdin: unexpected end of file
tar: Unexpected EOF in archive
tar: Unexpected EOF in archive
tar: Error is not recoverable: exiting now

I only see some of the data that is supposed to be in the archive, after running tar -xvzf archive.tgz I have tested this shell script extensively outside of expect and it works perfectly. What can I do?

RLE (2012-11-01): Best guess, your "expect -re" is triggering early on some content within the tgz file and sending the logout command before the entire tgz has been transferred. Then expect exits (because you've told it to exit after that) before the whole file is transferred.