Search code examples
passwordsexpectsendspawn

How can I implement SPAWN command with while loop to provide 'password' multiple times?


I'm trying to write a script where based on a given list of hostnames from input.txt file, I have to copy a file from the source server to the destination server for the user - alex.
Password is same for all hosts.

this asks for password every time and I tried SPAWN command with expect and send.

The below scripts give password automatically, only for the first prompt.

I'm aware there are other ways like SSH keys and password-less authentication.

But my exact requriement here is when I trigger the script - copying.sh it will ask multiple times for the "password", in this example 3 times as there are 3 different hosts and I should be able to send it from spawn_file.exp.

Can some one help me how can I implement it and what changes should I make ?

# copying.sh
#------------------------
while read line 
do
    scp /usr/file.txt  alex@${line}://home/temp/
done < input.txt 


#Spawn_file.exp
#------------------------
set timeout -1
spawn sh copying.sh
match_max 100000
expect -exact "Password: "
send -- "abcd1234"
expect eof


#input.txt
#------------------------ 
hostname1
hostname2
hostname3

Solution

  • THis is where you use the exp_continue command:

    #Spawn_file.exp
    #------------------------
    set timeout -1
    spawn sh copying.sh
    match_max 100000
    expect {
        -exact "Password: " {
            send -- "abcd1234"
            exp_continue
        }
        eof
    }
    

    That expect statemennt will wait for either "password" or eof.

    • If the password prompt is seen, the password will be send, and we'll "loop" in the expect statement
    • If eof is seen, there is no action, the expect statement ends, and then the expect script ends.