尝试grep时出现错误“期望:生成id id exp4未打开”

时间:2019-07-12 11:21:27

标签: bash expect

我正在尝试编译一个脚本,该脚本建立与远程计算机的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" }"

此代码有什么问题,导致其输出此错误, 感谢所有帮助

1 个答案:

答案 0 :(得分:1)

您可以使用一个命令来完成一个期望会话中的所有工作:

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用引号引起来。