尝试 grep 时出现错误 "expect: spawn id exp4 not open"

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

我正在尝试编译一个脚本来建立与远程机器的 ssh 连接并在多个日志文件中搜索错误消息,我当前的代码如下:

#!/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

现在您可能已经注意到我连接到机器 4 次,感觉效率很低,我尝试将所有这些日志搜索放入 1 个 ssh 连接中,如下所示:

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

但是当我尝试这个时我得到了错误

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

这段代码有什么问题导致它输出这个错误, 感谢所有帮助

您可以使用一个命令在一个 expect 会话中完成所需的所有工作:

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

您需要修改引号 " 标记和转义字符 \,以便远程 shell 不会解释它们。不需要用引号将字符串 error 引起来。