Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
937 views
in Technique[技术] by (71.8m points)

shell - Read file into String and do a loop in Expect Script

What I am trying to do is to:

  1. Create a .exp file, which will read from the *.txt file from the same directory and parse all the content in the text file into a string variable in the expect script.
  2. Loop the string, which contains a series of host names, and excecute a series of command until the string is enumerated.

So what the script does, is read a series of hostname from a txt file in the same directory, and then read them into a string, and the .exp file will auto log into each of them and excecute a series of commands.

I have the following code written but it's not working:

#!/usr/bin/expect

set timeout 20
set user test
set password test

set fp [open ./*.txt r]
set scp [read -nonewline $fp]
close $fp

spawn ssh $user@$host

expect "password"
send "$password
"

expect "host1"
send "$scp
"

expect "host1"
send "exit
"

Any help is greatly appreciated....

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The code should read the contents of the two files into lists of lines, then iterate over them. It ends up like this:

# Set up various other variables here ($user, $password)

# Get the list of hosts, one per line #####
set f [open "host.txt"]
set hosts [split [read $f] "
"]
close $f

# Get the commands to run, one per line
set f [open "commands.txt"]
set commands [split [read $f] "
"]
close $f

# Iterate over the hosts
foreach host $hosts {
    spawn ssh $user@host
    expect "password:"
    send "$password
"

    # Iterate over the commands
    foreach cmd $commands {
        expect "% "
        send "$cmd
"
    }

    # Tidy up
    expect "% "
    send "exit
"
    expect eof
    close
}

You could refactor this a bit with a worker procedure or two, but that's the basic idea.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...