【问题标题】:Unable to parse the output of command in expect script correctly无法正确解析期望脚本中的命令输出
【发布时间】:2014-01-21 22:55:57
【问题描述】:

我写了一个expect脚本来通过ssh登录远程机器并执行命令来获取系统信息细节。我能够登录到远程机器并运行命令并获得输出。我在解析输出时遇到了一些麻烦。我收到了一些不需要的文本和作为输出的一部分执行的命令,需要您的帮助来消除它们并获得相关的文本作为输出。

expect 脚本贴在下面

#!/usr/bin/expect

set timeout 10

log_user 0

set promptEn "(>|#|%|\\$)"

set ip [lindex $argv 0]

set user [lindex $argv 1]

set password [lindex $argv 2]

set query [lindex $argv 3]

if {[llength $argv] == 0} { 
  send_user "Usage: scriptname Ip-address Username password query\n"
  exit 1
}

spawn ssh -q -o StrictHostKeyChecking=no "$user\@$ip"

expect {
  timeout { send_user "\nFailed to get password prompt\n"; exit 1 }
  eof { send_user "\nSSH failure "; exit 1 }
  "*assword"
}

send "$password\r"

expect {
  timeout { send_user "\nLogin failed. Password incorrect.\n"; exit 1}
  #-re "$promptEn"
  -re $promptEn
}

send_user "\nPassword is correct\n"

#command to be executed 
send "sudo dmidecode -t system |grep -w \"$query:\"\r"

expect {
  timeout2 { send_user "\nFailed to get password prompt on remote machine \n"; exit 1 }
  eof { send_user "\nSSH failure "; exit 1 }
  "*assword"
}

send "$password\r"

expect {
  timeout
  { 
    send_user "\n Command Failed \n"; exit 1
  }

   -re "$promptEn"
}

expect -re "$query:" 



puts "$expect_out(buffer)"


send "exit\r"

我使用下面的命令行参数运行脚本

期望 sshtest.exp 192.168.4.42 testaccount Password@123 Manufacturer

我得到的解析输出为

Password is correct
 sudo dmidecode -t system |grep -w "Manufacturer:"
    Manufacturer: LENOVO
testaccount@santhosh-Lenovo-G560:~#

我只想要最后一行 Manufacturer: LENOVO 作为输出,而不是其他文本。

我可以如下调用脚本

expect sshtest.exp 192.168.4.42 testaccount Password@123 Manufacturer|tail -2 |head -1 接电话,但我不想这样做,因为如果系统无法连接,我会错过错误消息。

【问题讨论】:

    标签: automation expect


    【解决方案1】:

    在“密码正确”后添加:log_user 0

    然后,改变

    puts "$expect_out(buffer)"
    

    set lines [split $expect_out(buffer) \n]
    foreach line [lsearch -inline -glob $lines {*Manufacturer:*}] {
        puts $line
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-06
      • 1970-01-01
      • 2017-06-11
      • 1970-01-01
      • 1970-01-01
      • 2016-07-07
      • 2016-09-06
      • 2017-03-11
      相关资源
      最近更新 更多