问题描述
我尝试使用bash脚本中的 scp
将一些文件发送到多个服务器.但是我遇到了问题.
I try so send some files toward multiple servers using scp
in bash script.But I encountering problem.
这是我写的shell脚本.
here is the shell script I wrote.
#!/bin/sh
IP_LIST=('127.0.0.x' '127.0.0.y' '127.0.0.z')
for ip_addr in "${IP_LIST[@]}"
do
echo "$ip_addr"
expect << 'EOS'
set timeout 10
spawn scp -p /home/foo/bar/baz.txt user@"$ip_addr":/home/destdir
expect "*password*"
send "pasword\r"
expect eos
exit 0
EOS
done
我假设 ip_addr
中的每个元素都分配给变量 ip_addr
,但在 expect
会话中,未分配列表中的元素.
I assume each element in ip_addr
is assigned to the variable ip_addr
,but in expect
session, element in the list doesn't assigned.
当我执行此脚本时,会出现这样的错误消息.
When I execute this script, such error message appear.
can't read "ip_addr": no such variable
while executing
"spawn scp -p /home/foo/bar/baz.txt user@"$ip_addr":/home/destdir"
在使用 echo
命令(在 IP_LIST
中显示每个元素)时有效.
It works when use echo
command(displays each element in IP_LIST
).
有人知道一些好主意吗?
anybody know some good idea?
推荐答案
对于shell的<<STRING
语法,如果引用了 STRING
,则它不会扩展变量,因此您的 $ ip_addr
仍然是 $ ip_addr
到期望脚本,但未在期望中定义.您可以使用env var从 shell 将 ip_addr
从 shell 传递给 Expect .例如:
For shell's << STRING
syntax, if STRING
is quoted then it'll not expand variables so your $ip_addr
is still $ip_addr
to the Expect script but it's not defined in Expect. You can pass the ip_addr
from shell to Expect with the env var. E.g.:
#!/bin/sh
IP_LIST=('127.0.0.x' '127.0.0.y' '127.0.0.z')
for ip_addr in "${IP_LIST[@]}"
do
echo "$ip_addr"
ip_addr=$ip_addr expect << 'EOS'
set timeout 10
spawn scp -p /home/foo/bar/baz.txt user@$::env(ip_addr):/home/destdir
expect "*password*"
send "pasword\r"
expect eos; # do you mean `eof'?
exit 0
EOS
done
这篇关于如何在期望会话中使用shell变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!