我编写了一个脚本,该脚本将新密钥传输到我的AWS实例。脚本执行没有错误,但是当我检查实例上的〜/ .ssh / authorized_keys文件时,看不到新的SSH密钥。
这是脚本:
aws_instances=(
"ssh -i \"priv.pem\" ubuntu@99.99.99.1" #server1
"ssh -i \"priv.pem\" ubuntu@99.99.99.2" #server2
"ssh -i \"priv.pem\" ubuntu@99.99.99.3" #server3
)
IFS=""
for t in ${aws_instances[@]}; do
cat ~/newKey.pub | eval $t 'cat >> ~/.ssh/authorized_keys && echo "Key copied"'
done
它确实打印出“密钥已复制”
我更改了服务器的IP地址。
如果我只执行以下命令,它将起作用。
cat ~/newKey.pub | ssh -i "priv.pem" ubuntu@99.99.99.1 'cat >> ~/.ssh/authorized_keys && echo "Key copied"'
我的脚本怎么了?
答案 0 :(得分:4)
eval
是代码气味,请避免像害虫一样。
我认为您可以实现类似的功能:
#!/usr/bin/env bash
# See: https://tools.ietf.org/html/rfc5737
# 3. Documentation Address Blocks
#
# The blocks 192.0.2.0/24 (TEST-NET-1), 198.51.100.0/24 (TEST-NET-2),
# and 203.0.113.0/24 (TEST-NET-3) are provided for use in
# documentation.
# Array contains user-name@host-or-ip:ssh-port (ssh-port is optional, default standard 22)
aws_instances=(
'ubuntu@192.0.2.1'
'ubuntu@192.0.2.2:2222'
'ubuntu@192.0.2.3:2022'
)
new_keyfile="${HOME}/newKey.pub"
for instance in "${aws_instances[@]}"; do
ssh_host="${instance%%:*}" # trim the port if specified
port="${instance##*:}" # trim the host and keep port if specified
[[ ${port} == "${instance}" || -z "${port}" ]] && port=22 # use default port
if ssh-copy-id \
-i "${new_keyfile}" \
-p "${port}"
"${ssh_host}"; then
printf \
$"The new key file '%s' has been copied to user@host: '%s', port: %d.\\n" \
"${new_keyfile}" \
"${instance}" \
"${port}"
else
printf >&2 \
$"Could not copy the new key file '%s' to user@host: '%s', port: %d.\\n" \
"${new_keyfile}" \
"${instance}" \
"${port}"
fi
done
答案 1 :(得分:3)
您需要在第二个eval
参数周围加上引号。
例如:
cat ~/newKey.pub | eval $t "'"'cat >> ~/.ssh/authorized_keys && echo "Key copied"'"'"
问题在于,第一次调用eval时单引号会丢失,因此它将尝试执行的命令为
ssh -i "priv.pem" ubuntu@99.99.99.1 cat >> ~/.ssh/authorized_keys && echo "Key copied"
只是将ssh命令的输出附加到您的 local authorized_keys
文件中,而不是将密钥添加到远程主机中。
答案 2 :(得分:1)
有时候越简单越好。也许这样可以消除评估?
for i in 1 2 3
do ssh -i priv.pem ubuntu@99.99.99.$i 'cat >> ~/.ssh/authorized_keys &&
echo "Key copied" '< ~/newKey.pub
done
(在会议中,无法测试-警告脚本。)