'fetch variable in expect
I have the following vm's running on vmhost:
[root@server ~]# virsh list
Id Name State
----------------------------------------------------
2 vm1 running
3 xw-4530c running
4 optaserver running
I'm trying to fetch the name of the virtual machine starting with "xw" with an expect script, but it gives me all kinds of errors. I've replaced single quotes with curly brackets... because of... I think tcl? :) What is wrong with the set command below? The purpose with the script is to fetch the name, to run virsh reboot $xw ...
spawn ssh -o StrictHostKeyChecking=no $user@$host
expect "password:"
send "$password\r"
expect -re $prompt
send "virsh list\r"
expect -re $prompt
set xw [exec virsh list | grep xw | awk { { print \$2 } } ]
puts $xw
expect -re $prompt
Solution 1:[1]
For awk, the "outer" braces are Tcl's non-interpolating quotes: they already prevent variable substitution, so the awk $ does not need to be escaped.
However, exec is trying to launch virsh on your local machine not on the remote host.
This is where you need the expect_out variable which buffers the text going to and fro the spawned process.
send "virsh list\r"
expect -re $prompt
regexp -expanded -- { \m xw \S+ } $expect_out(buffer) xw
puts $xw
- read about
expect_outin your expect man page regexpis a Tcl command.\mis a regex assertion that matches an empty string at the start of a word;\Sis a non-space character
Thanks to Donal's suggestion:
send "virsh list\r"
set xw "not found"
expect {
-re {\m(xw\S+)} { # using capturing parentheses
set xw $expect_out(1,string)
exp_continue ;# continue to expect the prompt
}
-re $prompt
}
puts $xw
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
