Question

I have written an expect script to logon to remote machine through ssh and to execute commands to get the system information details . I'm able to login onto the remote machine and run commands and get the output . I have some trouble with parsing the output . I 'm getting some unwanted text and the command that i execute as a part of output , need your help in eliminating the same and get the relevant text as output .

The expect script is posted below

#!/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"

i run the script with the command line arguments as below

expect sshtest.exp 192.168.4.42 testaccount Password@123 Manufacturer

and i get the parsed output as

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

i just want the last but one line Manufacturer: LENOVO as the output but not the other text .

i can invoke the script as below

expect sshtest.exp 192.168.4.42 testaccount Password@123 Manufacturer|tail -2 |head -1 to get the line but i dont want to do that way as i will be missing out the error messages if the system cant be connected .

Was it helpful?

Solution

After "password is correct", add: log_user 0

Then, change

puts "$expect_out(buffer)"

to

set lines [split $expect_out(buffer) \n]
foreach line [lsearch -inline -glob $lines {*Manufacturer:*}] {
    puts $line
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top