我编写了一个期望脚本,通过ssh登录到远程机器并执行命令以获取系统信息详细信息。我能够登录到远程计算机并运行命令并获得输出。解析输出时遇到一些麻烦。我得到一些不需要的文本和我作为输出的一部分执行的命令,需要你的帮助来消除它并获得相关的文本作为输出。
期望脚本发布在
下面#!/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密码@ 123制造商
我将解析后的输出作为
Password is correct
sudo dmidecode -t system |grep -w "Manufacturer:"
Manufacturer: LENOVO
testaccount@santhosh-Lenovo-G560:~#
我只想要最后一行制造商:LENOVO 作为输出而不是其他文本。
我可以调用下面的脚本
expect sshtest.exp 192.168.4.42 testaccount Password@123 Manufacturer|tail -2 |head -1
获取该行,但我不想这样做,因为如果系统无法连接,我将错过错误消息。
答案 0 :(得分:1)
“密码正确”后,添加:log_user 0
然后,改变
puts "$expect_out(buffer)"
到
set lines [split $expect_out(buffer) \n]
foreach line [lsearch -inline -glob $lines {*Manufacturer:*}] {
puts $line
}