bash 在 shell 脚本中的 while 循环中运行 expect 命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25758983/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 21:40:02  来源:igfitidea点击:

Run expect command inside while loop in shell script

bashshellscriptingexpectscp

提问by Ramakrishna

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.shand passing each file name to transfer.shscript but scp is not executing command in this transfer script.If I run transfer.shalone with passing args its working fine.

我有一个文本文件中的文件名列表,需要使用 scp 命令将每个文件传输到服务器。我正在从Read.sh读取文件名并将每个文件名传递给transfer.sh脚本,但 scp 没有在此传输脚本中执行命令。如果我单独运行transfer.sh并传递 args 则它工作正常。

List.txt

列表.txt

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

Read.sh

读.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\r"
interact

I just run Read.sh as

我只是运行 Read.sh 作为

>./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.

它不执行下一条语句。请建议我任何解决方案。

回答by Ram

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

试试下面的脚本,变化是 Transfer.sh 被包装到 bash.sh 中。它在密码中等待的原因可能是因为您期待错误的模式,尝试“密码”而不是“密码”,然后在发送命令后,期待终端模式,以便 scp 完成

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