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
1.2k 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" user@192.168.4.151:/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 mbox140@192.168.4.151:/home/mbox140/Desktop/videos/
user@192.168.4.151'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 Reply

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 user@192.168.4.151:/home/user/Desktop/
    expect "Password"
    send "123
"
    expect "*#*"
EOF
}
done <List.txt

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

...