【发布时间】: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