ssh - Using Expect how do I exit foreach function after EOF -


after following script reads inventory file , completes commands testcommands file, foreach function looking more information inventory file process , errors rather ending.

#!/usr/bin/expect  set timeout 5  # open , read hosts file set fp [open "inventory_2ps"] set hosts [split [read $fp]"\n"] close $fp  # commands run in server set fh [open "testcommands"] set commands [split [read $fh] "\n"] close $fh  # set login variable set user "xxxxxxx"; set pw "xxxxxxx";  # spawn server login foreach host $hosts {      spawn ssh $user@$host     expect "$ "      send "su - xxxxxx\n"     expect "password: "      send "$pw\n"     expect "$ "      send "xxxxxx -nobash\r"     expect "> "      foreach cmd $commands {             send "$cmd\n"             expect "> "              }     expect eof 

receives error after last host login/exit:

>$ spawn ssh xxxxxx@" ssh: not resolve hostname ": name or service not known send: spawn id exp10 not open     while executing "send "su - xxxxxx\n""     ("foreach" body line 6)     invoked within "foreach host $hosts {      spawn ssh $user@$host     expect "$ " 

you need make sure code ignores blank values in input data because unhelpful in case. adding trivial filtering @ start of each foreach loop:

foreach host $hosts {     if {[string trim $host] eq ""} continue      spawn ssh $user@$host     # ... 

i use little bit more complex filtering (as below) can put comments in configuration files. nice in practice!

foreach host $hosts {     set host [string trim $host]     if {$host eq ""} continue     if {[string match "#*" $host]} continue      spawn ssh $user@$host     # ... 

quite apart this, make sure include space between text split , character set split by. might artefact of submission here, , not present in live code, matter quite bit tcl sensitive difference.


Comments

Popular posts from this blog

java - Jasper subreport showing only one entry from the JSON data source when embedded in the Title band -

mapreduce - Resource manager does not transit to active state from standby -

serialization - Convert Any type in scala to Array[Byte] and back -