Letho123
Letho123

Reputation: 129

getting error "expect: spawn id exp4 not open" while trying to grep

Im trying to compile a script that establishes an ssh connecting with a remote machine and searches multiple log files for error messages, my current code is the following:

#!/bin/bash

expect <<-EOF > /home/file
set timeout 3
spawn ssh -oPort=port ip zgrep "error" /dir/dir/file.gz.\[54321\]
expect "Are you sure you want to continue connecting (yes/no)?" { send "yes\r" }
expect "*password: " { send "password\r" }
expect "*#" { send "exit\r" }
EOF
expect <<-EOF >> /home/file
set timeout 3
spawn ssh -oPort=port ip zgrep "error" /dir/dir/file1.gz.\[54321\]
expect "Are you sure you want to continue connecting (yes/no)?" { send "yes\r" }
expect "*password: " { send "password\r" }
expect "*#" { send "exit\r" }
EOF
expect <<-EOF >> /home/file
set timeout 3 ip
spawn ssh -oPort=port ip  grep error /dir/dir/file
expect "Are you sure you want to continue connecting (yes/no)?" { send "yes\r" }
expect "*password: " { send "password\r" }
expect "*#" { send "exit\r" }
EOF
expect <<-EOF >> /home/file
set timeout 3
spawn ssh -oPort=port ip grep error /dir/dir/file1
expect "Are you sure you want to continue connecting (yes/no)?" { send "yes\r" }
expect "*password: " { send "password\r" }
expect "*#" { send "exit\r" }
EOF

Now have you may have noticed i connect to the machine 4 times, which feels so inefficient, i have tried to put all of this log searches into 1 ssh connection, like the following:

expect <<-EOF > /home/file
set timeout 3
spawn ssh -oPort=port ip zgrep "error" /dir/dir/file.gz.\[54321\]
expect "Are you sure you want to continue connecting (yes/no)?" { send "yes\r" }
expect "*password: " { send "password\r" }
expect "*#" { send "grep error /dir/dir/file1\r" }
expect "*#" { send "exit\r" }
EOF

but when i try this i get the error

spawn id exp4 not open
    while executing
"expect "*#" { send "grep error /dir/dir/file1\r" }"

What is wrong with this code that make it output this error, All help appreciated

Upvotes: 1

Views: 1499

Answers (1)

Paul Dawson
Paul Dawson

Reputation: 1382

You can use a single command to do all the work required in one expect session:

expect <<-EOF > /home/file
set timeout 3
spawn ssh -oPort=port ip "zgrep error /dir/dir/file.gz.[54321] ; zgrep error /dir/dir/file1.gz.[54321] ; grep error /dir/dir/file ; grep error /dir/dir/file1"
expect "Are you sure you want to continue connecting (yes/no)?" { send "yes\r" }
expect "*password: " { send "password\r" }
expect "*#" { send "exit\r" }
EOF

You will need to modify your quotation " marks and escape characters \ so that the remote shell does not to interpret them. There is no need to wrap the string error in quotation marks.

Upvotes: 1

Related Questions