Reputation: 67
I’m trying to write an expect loop that looks at a list of hosts in a text file then runs a series of commands from another text file named with the IP of the host and the file extension.txt
For example in the hosts.txt file I would have the following hosts defined:
192.168.1.1
192.168.3.1
192.168.2.197
Etc..
In another directory I would have files named as follows with a different set of commands that I wanted to run on each host:
192.168.1.1.txt 192.168.3.1.txt 192.168.2.197.txt
So if host 192.168.1.1 exists in hosts.txt, it runs the commands in 192.168.1.1.txt against that host. What would be the easiest vehicle in order to get this accomplished?
Upvotes: 1
Views: 333
Reputation: 137567
I'm not 100% sure, but part of the solution is:
# Read-a-file helper procedure
proc readFile {filename} {
set f [open $filename]
set content [read $f]
close $f
return $content
}
foreach host [split [readFile hosts.txt] "\n"] {
if {[catch { set commands [readFile $host.txt] }]} continue
spawn ssh $host
# ... handle connecting ...
# get a prompt ...
expect -ex "$ "
foreach line [split $commands "\n"] {
send $line\r
# Get the prompt
expect -ex "$ "
}
send "exit\r"
expect eof
close
}
That will give you the host and the commands to run against that host, skipping the absent files, then send each line of each of those files to the respective hosts, with setup and teardown of the connections all factored out. I've skipped things like how to handle passwords and there's much I'm not 100% sure about (I'm not a regular Expect user, so the expect eof
/close
might be wrong). It should look pretty similar to that.
You might instead consider making the command files be (partial) expect scripts that you just source
. That'd be a bit simpler in this code (at a cost of requiring those files to be a bit more complicated).
Upvotes: 1