我有下面一个脚本,除了预期部分外,其他都可以正常工作:
#!/bin/bash
#
invdir=/home/john/inventory
for file in $invdir/$1
do
if [ -z $1 ] || [ -z $2 ]
then
echo "You must enter a value: prod, dev, dr, or test AND the password of the env you entered"
exit 0
else
for host in `cat $file`
do
ssh-copy-id -i ~/.ssh/id_rsa.pub $host <<-EOF
expect "password:"
send "$2\n"
EOF
done
fi
done
我发现了一个可以满足我大部分需要的期望脚本:
#!/usr/bin/expect -f
spawn ssh-copy-id $argv
expect "password:"
send "your_password\n"
expect eof
to execute ./expect_script user@host1
我的问题是我对 bash 或 expect 了解不够,无法让这两个在一个 bash 脚本或 expect 脚本下工作。
先感谢您....
答案1
#!/bin/bash
#
invdir=/home/john/inventory
for file in "$invdir"/"$1"
do
if [[ -z "$1" ]] || [[ -z "$2" ]]
then
echo "You must enter a value: prod, dev, dr, or test AND the password of the env you entered"
exit 0
else
while IFS= read -r host
do
export host
export pw="$2"
expect <<'EOF'
spawn ssh-copy-id -i $env(HOME)/.ssh/id_rsa.pub $env(host)
expect "password:"
send "$env(pw)\n"
expect eof
EOF
done < "$file"
fi
done
一些说明:
- 注意引用你的 shell 变量,特别是位置参数
- 您需要启动期望解释器来运行期望代码
- 通过环境将 shell 变量传递给 expect
- 不要用以下方式读取文件的行
for
- 我不使用,
<<-EOF
因为对于 EOF 单词来说,使用非制表符太容易了。 - 但确实用来
<<'EOF'
保护预期变量