shell - 在 Expect 脚本中比较字符串的 If 条件

标签 shell tcl expect

我有一个期望脚本,我想在其中检查 uname -a。

如果远程服务器是Linux,那么我将使用expect运行更多远程命令。如果是 Aix,那么我将运行其他几组命令。但是我无法创建 if 条件。谁能帮帮我吗?

expect <<'EOF'
spawn ssh user_name@server "uname -a"
set count 0
expect {
"password:" {
send password\r
exp_continue
}
"Permission denied" {
    incr count
    exp_continue
  }
}
set strname LINUX

set results $expect_out(buffer)

if {$strname == $results}
{
puts $results
}
EOF

最佳答案

uname -a 命令输出不仅包含单词 LinuxAix,还包含更多信息。因此,最好使用regexp来检查它是否包含该单词。

#!/bin/bash
expect <<'EOF'
spawn ssh dinesh@xxx.xxx.xx.xxx "uname -a"
set count 0
expect {
    timeout {puts "timeout happened"}
    eof {puts "eof received"}
    "password:" {send "password\r";exp_continue}
    "Permission denied" {incr count;exp_continue}
}

set results $expect_out(buffer)

if {[regexp -nocase "Linux" $results]} {
        puts "It is a Linux Machine"
} elseif {[regexp -nocase "Aix" $results]} {
        puts "It is a AIX machine"
} else {
        puts "Unknown machine"
}
EOF

否则,您应该单独使用 uname 命令,它只会生成我们确实需要的内容。在这种情况下,您给定的代码将正常工作。

关于shell - 在 Expect 脚本中比较字符串的 If 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33174807/

相关文章:

bash - 运行 shell 脚本时如何解决 "shift: can' t shift the many"错误?

linux - 使用 'expect'命令远程传递密码给SSH运行脚本

预期脚本 : How to provide default values if arguments are not passed

linux - 外推——基于 awk

r - 来自 Shell 的 R CMD BATCH 模式中的参数

linux - if else 语句错误检查

centos - 错误 'bad pad value "2m": must be positive screen distance' when using tk_messageBox on a wayland display (CentOS)

regex - 在 Tcl 中实现 "quotemeta"\Q ...\E ?

c# - 在 C# 中的不同堆栈上驱动相同 API 的优雅方法是什么

linux - 使用 expect 时需要使用 spawn 吗?