【问题标题】:Run expect command inside while loop in shell script在shell脚本的while循环中运行expect命令
【发布时间】:2014-11-03 17:20:21
【问题描述】:

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

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

我只是运行 Read.sh

>./Read.sh

输出:

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

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

【问题讨论】:

  • 你试过独立运行 transfer.sh 吗?并且在 transfer.sh 中,interact 命令应该抛出错误,因为您正在尝试与关闭的进程(在本例中为 scp )进行通信
  • @Ram 是的,转移作为独立工作。

标签: bash shell scripting expect scp


【解决方案1】:

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

#!/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\r"
    expect "*#*"
EOF
}
done <List.txt

【讨论】:

  • 感谢您的评论,我在这里尝试了上面的代码我收到了语法错误和警告:here-document at line 4 delimited by end-of-file (wanted `EOF') 语法错误:意外文件结束
  • 问题是由于复制粘贴错误,你必须删除每行开头的多余空格,试试这个命令“sed -i 's/^ *//g' filename” over脚本并重新运行脚本,抱歉格式错误
  • 嘿,我刚刚删除了 echo $p,它的工作原理。感谢您的回答。
  • 是否可以在while循环中删除与$p匹配的行。因为一旦文件传输到服务器,我想从List.txt中删除文件名。???
  • 你指的是“spawn scp $p user@192.168.4.151:/home/user/Desktop/”这行吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多