Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

bash - Run expect command inside while loop in shell script

I have list of filenames in a text file,need to transfer each file into server using scp command.I am reading filenames from Read.sh and passing each file name to transfer.sh script but scp is not executing command in this transfer script.If I run transfer.sh alone with passing args its working fine.

List.txt

/home/kittu/file1.txt
/home/kittu/file2.txt
/home/kittu/file3.txt

Read.sh

#!/bin/bash
while read p; do
  echo $p
    ./transfer.sh "$p"
done <List.txt

transfer.sh

#!/usr/bin/expect -f

# get filename from command-line
set f [lindex $argv 0]

spawn scp "$f" [email protected]:/home/user/Desktop/ 
expect "password"
send "123
"
interact

I just run Read.sh as

>./Read.sh

Output:

/home/user/Desktop/file1.txt
spawn scp /home/mbox140/Desktop/test.sh [email protected]:/home/mbox140/Desktop/videos/
[email protected]'s password:

Its not executing next statement.Please suggest me any solution.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Try the below script , The changes are that the Transfer.sh is wrapped into bash.sh. and the reason it waits in the password may be because you are expecting a wrong pattern , try "Password" instead of "password" and after send command, expect for the terminal pattern so that the scp finishes

#!/bin/bash
while read p; do
echo $p
{
    /usr/bin/expect << EOF
    spawn scp $p [email protected]:/home/user/Desktop/
    expect "Password"
    send "123
"
    expect "*#*"
EOF
}
done <List.txt

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.6k users

...