期待脚本检查/ var / log / message

时间:2016-06-20 05:47:50

标签: tcl sh expect

在预期的脚本中,当我通过ssh远程登录系统然后执行sudo su -时,我想检查/var/log/secure中是否有特定的字符串,如果该字符串存在则在屏幕上显示输出或不(发送" grep ....)

expect << 'EOF'
    spawn ssh -q $env(U1)@$env(S1)
    expect "password:" {
        send $env(P1)\r
    }
    expect "$env(U1)@$env(S1)" {
        send "sudo su - \r"
    }
    expect "password" {
        send $env(P1)\r
    }

    expect  {
        "# " {
            send "grep 'pam_unix(su-l:session): session opened for user root by' /var/log/secure"
        }
        "Authentication failure" {
            send_user "Su ROOT  Fail ...... Fail\n"
            send \x03
        }
    }
EOF

1 个答案:

答案 0 :(得分:1)

由于您正在搜索特定字符串,因此最好使用fgrep。如果你只关心字符串是否存在,而不是它周围是否还有其他东西,你可以使用-q选项和一点shell技巧来获得一个易于处理的结果:

fgrep -q '....' /var/log/secure && echo FOUND || echo ABSENT

接下来,您需要以适用的方式将其插入到您的expect脚本中。特别是,如果发生提升失败,我们需要确保代码运行搜索:

# Factored out for line-length reasons. :-)
set searchTerm "pam_unix(su-l:session): session opened for user root by"
expect  {
    "# " {
        send "fgrep -q '$searchTerm' /var/log/secure && echo FOUND || echo ABSENT"
    }
    "Authentication failure" {
        send_user "Su ROOT  Fail ...... Fail\n"
        send \x03
        #### STOP THE EXPECT SCRIPT RUNNING!
        close
        exit 1
    }
}
expect {
    "FOUND" {
        # ...
    }
    "ABSENT" {
        # ...
    }
}

编写一个好的Expect脚本的艺术是预测失败模式。此外,您可能应该使用send "exec sudo su -\r",以便提升会话的结束也是整个会话的结束。